如果使用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);
這是[生產者消費者問題](http://en.wikipedia.org/wiki/Producer-consumer_problem)。也許那篇文章會給你一些見解。 – jpm 2012-04-13 17:06:51
@jpm非常感謝你,我會讀它.. – 2012-04-13 17:12:36