假设我有以下代码:

final ExecutorService threadPool = Executors.newFixedThreadPool(
    NUMBER_OF_WORKERS);

for (int i=0; i < NUMBER_OF_WORKERS; i++)
{
  final Worker worker = new BirthWorker(...);
  threadPool.execute(worker);
}

现在,我需要一段代码,等待所有 worker 完成工作。

我知道的选项:
  • while (!threadPool.isTerminated()) {}
  • 像这样修改代码:

    最终列表 future =新的ArrayList(NUMBER_OF_WORKERS);
    最终的ExecutorService threadPool = Executors.newFixedThreadPool(NUMBER_OF_WORKERS);

    为(int i = 0; i {
    最终工作人员=新工作人员(...);
    futures.add(threadPool.submit(worker));
    }

    对于(最终 future future : future ){
    future.get();
    }

    //当我们到达这里时,保证所有 worker 都已完成工作。

  • 等待所有 worker 完成工作的最佳实践是什么?

    最佳答案

    我建议您使用CountDownLatch(假设这是一次 Activity ),在构造函数中,您可以指定要等待的线程数,并在线程中共享该实例,然后使用await api等待所有线程完成(使用超时或完全阻止)以及完成后线程的调用countdown api。

    另一个选择是,如果您有权访问要完成的​​每个线程,则在线程中调用join方法以等待其完成。

    关于java - 等待线程池中所有工作程序完成的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28911912/

    10-11 22:58
    查看更多