如何使用执行器服务等待所有线程完成?

我需要一次执行4个任务,如下所示:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    taskExecutor.execute(new MyTask());
}
//...wait for completion somehow

完成所有操作后,如何获得通知?就目前而言,我想不出比设置一些全局任务计数器并在每个任务结束时减少它更好的事情了,然后在无限循环中监视此计数器变为0;或者获取期货列表,并在无限循环监视器中为所有这些产品提供解决方案。不涉及无限循环的更好解决方案是什么?

谢谢。


答案 1

基本上,在执行器服务上,你调用 shutdown() 然后 awaitTermination()

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}
taskExecutor.shutdown();
try {
  taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  ...
}

答案 2

使用倒计时闩锁

CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
  taskExecutor.execute(new MyTask());
}

try {
  latch.await();
} catch (InterruptedException E) {
   // handle
}

并在您的任务中(包含在尝试/最后)

latch.countDown();

推荐