美文网首页
2019-10-12

2019-10-12

作者: 九度_09e3 | 来源:发表于2019-10-12 10:54 被阅读0次

    countDownLatch

    1.背景:

    countDownLatch是在java1.5被引入,跟它一起被引入的工具类还有CyclicBarrier、Semaphore、concurrentHashMap和BlockingQueue。

    存在于java.util.cucurrent包下。

    2.概念

    countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。

    是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

    3.源码

    countDownLatch类中只提供了一个构造器:

    //参数count为计数值public CountDownLatch(int count) {  };

    类中有三个方法是最重要的:

    //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行publicvoidawait()throwsInterruptedException{};//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行publicbooleanawait(longtimeout,TimeUnitunit)throwsInterruptedException{};//将count值减1publicvoidcountDown(){};

    4.示例

    普通示例:

    publicclassCountDownLatchTest{publicstaticvoidmain(String[]args){finalCountDownLatchlatch=newCountDownLatch(2);System.out.println("主线程开始执行…… ……");//第一个子线程执行ExecutorServicees1=Executors.newSingleThreadExecutor();es1.execute(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(3000);System.out.println("子线程:"+Thread.currentThread().getName()+"执行");}catch(InterruptedExceptione){e.printStackTrace();}latch.countDown();}});es1.shutdown();//第二个子线程执行ExecutorServicees2=Executors.newSingleThreadExecutor();es2.execute(newRunnable(){@Overridepublicvoidrun(){try{Thread.sleep(3000);}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("子线程:"+Thread.currentThread().getName()+"执行");latch.countDown();}});es2.shutdown();System.out.println("等待两个线程执行完毕…… ……");try{latch.await();}catch(InterruptedExceptione){e.printStackTrace();}System.out.println("两个子线程都执行完毕,继续执行主线程");}}

    结果集:

    主线程开始执行…… ……等待两个线程执行完毕…… ……子线程:pool-1-thread-1执行子线程:pool-2-thread-1执行两个子线程都执行完毕,继续执行主线程

    模拟并发示例:

    publicclassParallellimit{publicstaticvoidmain(String[]args){ExecutorServicepool=Executors.newCachedThreadPool();CountDownLatchcdl=newCountDownLatch(100);for(inti=0;i<100;i++){CountRunnablerunnable=newCountRunnable(cdl);pool.execute(runnable);}}}classCountRunnableimplements Runnable{privateCountDownLatchcountDownLatch;publicCountRunnable(CountDownLatchcountDownLatch){this.countDownLatch=countDownLatch;}@Overridepublicvoidrun(){try{synchronized(countDownLatch){/*** 每次减少一个容量*/countDownLatch.countDown();System.out.println("thread counts = "+(countDownLatch.getCount()));}countDownLatch.await();System.out.println("concurrency counts = "+(100-countDownLatch.getCount()));}catch(InterruptedExceptione){e.printStackTrace();}}}

    *CountDownLatch和CyclicBarrier区别:

    1.countDownLatch是一个计数器,线程完成一个记录一个,计数器递减,只能只用一次

    2.CyclicBarrier的计数器更像一个阀门,需要所有线程都到达,然后继续执行,计数器递增,提供reset功能,可以多次使用

    注:内容转载自https://www.jianshu.com/p/e233bb37d2e6

    相关文章

      网友评论

          本文标题:2019-10-12

          本文链接:https://www.haomeiwen.com/subject/csxqmctx.html