Java并发组件一之CountDownLatch

作者: TTLLong | 来源:发表于2019-07-30 20:06 被阅读6次

    CountDownLatch

    相关文章:
    1. CountDownLatch
    2. CyclicBarriar--循环屏障
    3. Semaphore--信号量
    使用场景:

    一个或N个线程,等待其它线程完成某项操作之后才能继续往下执行。CountDownLatch描述的是,一个或N个线程等待其他线程的关系。

    使用方法:
    1. 设CountDownLatch个数:CountDownLatch countDownLatch=new CountDownLatch(3);
    2. 在等待线程中await:countDownLatch.await();
    3. 在其他线程中减少count值:countDownLatch.getCount();
    4. 一旦其他线程中的countDownLatch.getCount()的次数为实例化时的count值,就唤醒等待线程
    /**
     * 作者:jtl
     * 日期:Created in 2019/7/29 14:59
     * 描述:CountDownLatch 例子
     * 更改:
     */
    
    class CountDownLatchExample {
        private static final int total=200;
        
        public static void main(String[] args) throws InterruptedException{
            ExecutorService executorService = Executors.newCachedThreadPool();
            CountDownLatch countDownLatch=new CountDownLatch(total);
            for (int i=0;i<total;i++){
                final int threadNum=i;
                executorService.execute(()-> {
                    test(threadNum,countDownLatch.getCount());
                    countDownLatch.countDown();
                });
            }
    
            countDownLatch.await();
            System.out.println("CountDownLatch --- finish:"+countDownLatch.getCount());
    
            executorService.shutdown();
        }
    
        private static void test(int time,long count){
            System.out.println(time+" --- "+count);
        }
    }
    

    相关文章

      网友评论

        本文标题:Java并发组件一之CountDownLatch

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