CountDownLatch:用于多线程并行执行
例:
@Slf4j
public class CountDownLatchDemo {
private static volatile int index = 0;
public static void main(String[] args) throws InterruptedException {
//创建倒计数器,指定计数数量为3
CountDownLatch countDownLatch = new CountDownLatch(3);
ThreadPoolManager.ThreadPool threadPool = ThreadPoolManager.getThreadPool();
for (int i = 1; i < 4; i++) {
int s=++index;
threadPool.execute(() -> {
log.info(s + " runing " + System.currentTimeMillis());
try {
Thread.sleep(1000);
log.info(s + " run end " + System.currentTimeMillis());
} catch (InterruptedException e) {
log.error(e.getMessage(), e);
} finally {
//通知CountDownLatch有一个线程已经准备完毕,倒计数器可以减一了
countDownLatch.countDown();
}
});
}
//要求主线程需等所有线程准备好后,并行执行完毕后才能继续执行
countDownLatch.await();
//关闭线程池
threadPool.shutdown();
log.debug("main Thread end");
}
}
ThreadPoolManager.ThreadPool为自写的一个线程池工具,代码详情
输出:
1 runing 1564386456075
2 runing 1564386456076
3 runing 1564386456076
2 run end 1564386457080
1 run end 1564386457080
3 run end 1564386457080
main Thread end
各线程执行顺序可能与输出不一致,但是主线程必须在CountDownLatch倒计数器执行为0时才会继续执行。
注意:
- CountDownLatch指定计数数量如小于线程数,那么超出的线程将可能不能达到并行的要求;
- CountDownLatch指定的计数数量大于线程数,那主线程将无法执行完毕。