我正在使用ExecutorService創建線程池。添加完所有任務後,threadPool將關閉。我是否需要在future.get()之後使用threadPool.awaitTermination;
現在Java文檔的Future.get()說
如有必要,等待計算完成,然後獲取其結果。
我無法理解「必要」部分。 future.get()方法何時等待以及它將等待多少時間? 如果它等到線程執行結束,是否需要threadPool.awaitTermination?
ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
List<Future<?>> futureObjList = new ArrayList<Future<?>>();
for (int i = 0; i < numberOfThreads; i++) {
...
Future<?> future = threadPool.submit(myThread);
futureObjList.add(future);
...
}
threadPool.shutdown();
for(Future<?> future : futureObjList){
try {
future.get();
} catch (Exception e1) {
//if any thread fails, all other thread should stop their execution.
threadPool.shutdownNow();
}
}
try {
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e1) {
throw e1;
}
假設我有10個線程。所有線程都需要隨機的時間來完成。考慮第4或第5個線程拋出RuntimeException。現在,如果我正在迭代未來的對象,那麼它將捕獲異常,其餘線程將被關閉。但是如果我等待終止,它將不會存在,直到所有線程都完成。 –
如果你的要求是如果任何線程失敗,停止所有的線程,那麼它是有道理的循環。在這種情況下,您不需要awaitTermination(),因爲線程在循環完成後將完成執行。但是,這是不可靠的,因爲當你到達一個失敗的線程時,所有其他線程可能已經完成,並且沒有關閉它們的任何一點。如果任何線程發生故障,您可能不得不考慮設置一個標誌,如果設置該線程可以關閉所有其他線程。 – Priyesh