等待线程池所有线程执行结束

484 阅读1分钟

等待线程池所有线程执行结束

方法一:pool.awaitTermination(..)

List<SalesSummaryVO> res = Lists.newArrayList();
for (StatisticsGoodsType value : StatisticsGoodsType.values()) {
threadPoolExecutor.execute(() -> task(startDate, endDate, res, value));
}
threadPoolExecutor.shutdown();
try {
threadPoolExecutor.awaitTermination(30L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}

方法二:CountDownLatch

CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);// 任务数
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}
try {
  latch.await();
} catch (InterruptedException E) {
   // handle
}

// task中完成任务或异常执行countDown()
try {
  ...
} catch (Exception e) {
  e.printStackTrace();
}finally {
  countDownLatch.countDown();
}