CountDown 倒计时,Latch 锁存器,CountDownLatch 整体是一个倒计时锁存器
//调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public void await() throws InterruptedException { };
//和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };
//将count值减1
public void countDown() { };
final CountDownLatch countDownLatch = new CountDownLatch(3);
ExecutorService threadPool = Executors.newFixedThreadPool(3);
for (MediaCodeType mediaCode : MediaCodeType.values()) {
threadPool.submit(() -> {
try {
// 业务代码块
long t21 = System.currentTimeMillis();
long t22 = System.currentTimeMillis() - t21;
logger.info(mediaCode.getDesc() + "买量数据已保存,耗时:" + (t22 / 60000) + "分" + (t22 % 60000) / 1000 + "秒" + (t22 % 60000) % 1000 + "毫秒");
// MailUtils.send(mediaCode.getDesc() + "买量数据已保存", "耗时:" + (t22 / 60000) + "分" + (t22 % 60000) / 1000 + "秒" + (t22 % 60000) % 1000 + "毫秒", "wangxy2", null, null);
} catch (Exception e) {
logger.error(ExceptionCollect.collectExceptionStackMsg(e));
} finally {
// 会将count减1,直至为0
countDownLatch.countDown();
}
});
}
try {
// 调用此方法的线程会被阻塞,直到监听CountDownLatch的count为0
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
// 主程序代码块
......
参考文献:
1.Java并发编程:CountDownLatch、CyclicBarrier和Semaphore - Matrix海子 - 博客园