如果您使用ExecutorService
来运行您的线程作业,那么您可以使用该awaitTermination()
方法来了解所有线程何时完成:
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(yourSolutionsRunnable);
pool.submit(yourSolutionsRunnable);
...
// once you've submitted your last job you can do
pool.shutdown();
然后您可以等待所有提交的作业完成:
pool.waitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
如果您的线程在提交解决方案后需要继续运行,这将变得更加复杂。如果您编辑您的问题并使其更加明显,我将编辑我的答案。
编辑:
哦,我看到您想在此过程中处理一些结果,但在所有线程完成之前不要停止。
您可以使用pool.isTerminated()
测试来告诉您是否所有工作都已完成。所以你的循环看起来像:
// this is the main thread so waiting for solutions in a while(true) loop is ok
while (true) {
// are all the workers done?
if (pool.isTerminated()) {
// if there are results process one last time
if (!solutions_results.isEmpty()) {
processTheSolutions();
}
break;
} else {
if (solutions_results.isEmpty()) {
// wait a bit to not spin, you could also use a wait/notify here
Thread.sleep(1000);
} else {
processTheSolutions();
}
}
}
编辑:
您还可以有两个线程池,一个用于生成解决方案,另一个用于处理。然后,您的主线程可以等待工作池清空,然后等待解决方案处理池。工作池会将解决方案(如果有)提交到解决方案池中。您可以在解决方案处理池中只有 1 个线程,或者根据需要更多。
ExecutorService workerPool = Executors.newFixedThreadPool(10);
final ExecutorService solutionsPool = Executors.newFixedThreadPool(1);
solutionsPool.submit(workerThatPutsSolutionsIntoSolutionsPool);
...
// once you've submitted your last worker you can do
workerPool.shutdown();
workerPool.waitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
// once the workers have finished you shutdown the solutions pool
solutionsPool.shutdown();
// and then wait for it to finish
solutionsPool.waitTermination(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);