新Java并发线程控制:CountDownLatch等待所有线程运行完毕才执行

新Java并发线程控制:CountDownLatch等待所有线程运行完毕才执行

创建一批Java线程,然后这批Java线程几乎同时全部跑起来,但是有些开发场景下,开发者需要等到这些Java线程全部执行完毕后,才去执行接下去的业务流程。这个时候就可以CountDownLatch就可以派上用场,CountDownLatch是Java语言从1.5引入的线程控制类,

* A synchronization aid that allows one or more threads to wait until
* a set of operations being performed in other threads completes.

CountDownLatch在创建之初的构造函数时候需要传递一个count值,这个值作为计数器,在每一个Java线程运行完毕后,通过CountDownLatch的countDown()函数,给CountDownLatch维护的计数(count值)减1,当CountDownLatch的countDown()把计数器减至0时候,CountDownLatch的await()函数阻塞状态解除,就可以接着继续执行后续逻辑代码。
如代码:

    private void test() {
        int count = 5;

        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new WorkThread(i, countDownLatch).start();
        }

        try {
            System.out.println("等待" + count + "个线程运行完毕...");
            countDownLatch.await();

            System.out.println(count + "个线程已运行完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class WorkThread extends Thread {
        private int seq;
        private CountDownLatch countDownLatch;

        public WorkThread(int seq, CountDownLatch countDownLatch) {
            this.seq = seq;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                System.out.println("线程" + this.seq + "开始运行...");
                Thread.sleep(2000);
                System.out.println("线程" + this.seq + "运行结束");

                countDownLatch.countDown();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

输出:

2018-10-27 10:20:00.727 26486-26486/zhangphil.test I/System.out: 等待5个线程运行完毕...
2018-10-27 10:20:00.728 26486-26513/zhangphil.test I/System.out: 线程4开始运行...
2018-10-27 10:20:00.728 26486-26512/zhangphil.test I/System.out: 线程3开始运行...
2018-10-27 10:20:00.728 26486-26510/zhangphil.test I/System.out: 线程1开始运行...
2018-10-27 10:20:00.728 26486-26508/zhangphil.test I/System.out: 线程0开始运行...
2018-10-27 10:20:00.729 26486-26511/zhangphil.test I/System.out: 线程2开始运行...
2018-10-27 10:20:02.728 26486-26513/zhangphil.test I/System.out: 线程4运行结束
2018-10-27 10:20:02.729 26486-26512/zhangphil.test I/System.out: 线程3运行结束
2018-10-27 10:20:02.729 26486-26510/zhangphil.test I/System.out: 线程1运行结束
2018-10-27 10:20:02.729 26486-26508/zhangphil.test I/System.out: 线程0运行结束
2018-10-27 10:20:02.729 26486-26511/zhangphil.test I/System.out: 线程2运行结束
2018-10-27 10:20:02.730 26486-26486/zhangphil.test I/System.out: 5个线程已运行完毕

附:
1,《新Java线程Semaphore:并行环境下访问竞争资源控制》链接:https://blog.csdn.net/zhangphil/article/details/83410270 

 

你可能感兴趣的:(Java,Java多线程)