如何使用ExecutorService等待所有线程完成?

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

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

一旦所有人都完成了,我怎样才能得到通知? 现在我无法想象设置一些全局任务计数器并在每个任务结束时减少它,然后在无限循环中监视此计数器变为0; 或者得到一份期货清单,并在无限循环监控isDone的所有人。 什么是不涉及无限循环的更好的解决方案?

谢谢。


基本上在ExecutorService调用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) {
  ...
}

使用CountDownLatch:

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

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

并在你的任务内(最后尝试)

latch.countDown();

ExecutorService.invokeAll()为你做。

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete
List<Future<?>> futures = taskExecutor.invokeAll(tasks);
链接地址: http://www.djcxy.com/p/92053.html

上一篇: How to wait for all threads to finish, using ExecutorService?

下一篇: What are the advantages of using an ExecutorService?