利用CountDownLatch在多线程中的使用
在代码中无时不用到线程,当我们需要等待一组多线程执行完以后,再进行某些逻辑时,我们可以用submit的callback,也可以利用CountDownLatch的await来实现等待所有线程执行完成。
int s = 10;
final CountDownLatch latch = new CountDownLatch(s);
// 考虑调度中心发起终止任务,使用局部变量。
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(threadNumber);
taskExecutor.setMaxPoolSize(threadNumber);
taskExecutor.initialize();
for (int i = 0; i < s; i++) {
taskExecutor.execute(() -> doTask(latch));
}
try {
if (!latch.await(20, TimeUnit.MINUTES)) {
LOGGER.error("{}", "=====> 阻塞等待所有线程结束出现超时");
}
} catch (InterruptedException e) {
LOGGER.error("=====> 阻塞等待所有线程结束出现异常", e);
Thread.currentThread().interrupt();
} finally {
taskExecutor.shutdown();
}
private void doTask(CountDownLatch latch) {
try {
System.out.println("running");
} catch (Exception e) {
LOGGER.error("=====> 刊登出现异常", e);
} finally {
latch.countDown();
}
}
利用await方法一直等待计数器为0,如果为0说明所有线程的逻辑代码全部执行完成。