zoukankan      html  css  js  c++  java
  • 24.Semaphore

    Semaphore
        在进程方面完成信号线的控制,可以控制某个资源下,可被同时访问的线程个数。对系统的访问量进行评估,信号量维护了一个许可集;在许可前会阻塞每一个 semaphore.acquire() ,然后再获取该许可,每一个release() 添加一个许可,从而
        可能释放一个正在阻塞的获取者,但是,不使用实际的许可对象,Semaphore只对可用许可的号码进去计算,并采取行动,拿到信号量的线程则进入代码,否则就等待。
    semaphore.acquire();//1.获取许可
    semaphore.release();//3.访问完毕,释放
    1. package demo1;
    2. import java.util.concurrent.ExecutorService;
    3. import java.util.concurrent.Executors;
    4. import java.util.concurrent.Semaphore;

    5. public class DemoSemaphore {

    6. public static void main(String[] args) {
    7. ExecutorService executorService = Executors.newCachedThreadPool();
    8. Semaphore semaphore = new Semaphore(3);
    9. for (int i=0;i<=20;i++){
    10. final int no =i;
    11. Runnable runnable = new Runnable() {
    12. @Override
    13. public void run() {
    14. try {
    15. semaphore.acquire();//1.获取许可
    16. System.err.println("systme:"+no);
    17. Thread.sleep((long) (Math.random()*1000));//2.模拟业务耗时
    18. semaphore.release();//3.访问完毕,释放 ,如果屏蔽下面的语句,则在控制台只能打印5条记录,之后线程一直阻塞
    19. } catch (InterruptedException e) {
    20. e.printStackTrace();
    21. }finally {
    22. System.err.println("。。。");
    23. }
    24. }
    25. };
    26. executorService.execute(runnable);
    27. }
    28. executorService.shutdown();
    29. }
    30. }
    31. 输出:
    32. systme:0 systme:1 systme:2 。。。 systme:3 。。。 systme:4 。。。 systme:5 。。。 systme:6 。。。 systme:7 。。。 systme:8 。。。 systme:9 。。。 systme:10 。。。 systme:11 。。。 systme:12 。。。 systme:13 。。。 systme:14 。。。 systme:15 。。。 systme:16 。。。 systme:17 。。。 systme:18 。。。 systme:19 。。。 systme:20 。。。 。。。 。。。
  • 相关阅读:
    初学java
    位操作运算符的最好的解释
    C++手机通讯录排序
    删除TFS项目上的文件
    单元测试中方法运行测试和调试测试不起作用原因
    EF-CodeFirst系列100
    NPOI-Excel系列-1002.创建带有Document Summary Information和Summary Information的Excel文件
    NPOI-Excel系列-1000.创建一个标准的Excel文件
    T4模板批量生成代码文件
    WebService返回json格式数据供苹果或者安卓程序调用
  • 原文地址:https://www.cnblogs.com/xxt19970908/p/7337131.html
Copyright © 2011-2022 走看看