CountDownLatch线程计数器的作用

阅读 77

2021-09-30

简述

CountDownLatch(N)指定自己是N个线程的计数器,每个线程执行到特定的环节可以count一下,这样CountDownLatch就会计数一次,一旦计数达到CountDownLatch定义的N次,那么阻塞在latch.await()的线程的代码就会继续往下执行。
btw,latch中文意思是门闩,也就是也有锁的意思~

示例代码

场景:主线程要等待两个子线程执行完才能继续执行。主线程启完2个子线程后在latch.await()阻塞等待,子线程自己执行完自己的逻辑之后去CountDownLatch上latch.countDown()计数一下,一旦CountDownLatch计数达到了2次,则主线程代码会从latch.await()继续往下执行。

CountDownLatch latch = new CountDownLatch(2);
        // 第一个子线程
        new Thread(new Runnable() {

            @Override
            public void run() {
                logger.info("子线程" + Thread.currentThread().getName() + "正在执行");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.info("子线程" + Thread.currentThread().getName() + "执行完毕");
                latch.countDown(); //自己执行完了,去latch上计数一次
            }

        }).start();
        // 第二个子线程
        new Thread(new Runnable() {

            @Override
            public void run() {
                logger.info("子线程" + Thread.currentThread().getName() + "正在执行");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                logger.info("子线程" + Thread.currentThread().getName() + "执行完毕");
                latch.countDown(); //自己执行完了,去latch上计数一次
            }

        }).start();
        
        logger.info("主线程"+Thread.currentThread().getName()+"等待两个子线程执行完毕...");
        latch.await(); //阻塞等待latch的计数达到两次之后再继续执行
        logger.info("两个子线程已执行完毕");
        logger.info("继续执行主线程");

运行结果:

主线程main等待两个子线程执行完毕...
子线程Thread-2正在执行
子线程Thread-1正在执行
子线程Thread-1执行完毕
子线程Thread-2执行完毕
两个子线程已执行完毕
继续执行主线程

精彩评论(0)

0 0 举报