如何使用CountDownLatch等待所有线程运行完毕才停止呢?
下文笔者讲述CountDownLatch等待所有线程运行完毕,再继续详细运行的方法分享,如下所示
CountDownLatch所有线程完毕,再详细运行的实现思路
1.初始化一个CountDownLatch线程数
1.1 每次线程运行完毕后,调用latch.countDown递减一次
2.调用await()使线程阻塞
直到所有线程运行完毕,则向下继续运行
例
ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
CountDownLatch latch = new CountDownLatch(2);
for(int i = 0;i< 2; i++){
WORKER_THREAD_POOL.submit(() -> {
try {
// ...
latch.countDown();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
// wait for the latch to be decremented by the two remaining threads
latch.await();
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


