まず第一に、 に渡す時間awaitTermination
はおおよその値であり、すべてのタスクを完了するのにかかった最悪の累積時間よりも常に長くなる必要があります。それらのランナブルで実行しているのが Web サービス呼び出しまたは DB 呼び出しである場合、サイトのトラフィックに基づいて異なる可能性があるため、一定の時間を推測しないのは簡単ではありません。そのため、特定の時間内に常に完了すると想定するのではなく、すべてのランナブルが完了するのを待ってから、それらの結果を利用し始める必要があります。
CompletableFuture
Java8 から使用できず、プールに送信されたすべてのランナブルが実行されるまで待機する必要がある場合は、以下のようinvokeAll
に onを使用できExecutorService
ます。
invokeAll
送信されたすべての callable が実行されるまで、メイン スレッドをブロックします。
// removing try-catch blocks for brevity
ExecutorService service = Executors.newFixedThreadPool(2);
List<Callable<Integer>> tasks = new ArrayList<>();
tasks.add(new Callable<Integer>(){
public Integer call(){
Thread.sleep(5000);
System.out.println("thread1 coming out of sleep");
return 1;
}
});
tasks.add(new Callable<Integer>(){
public Integer call(){
Thread.sleep(10000);
System.out.println("thread2 coming out of sleep");
return 2;
}
});
List<Future<Integer>> futures = service.invokeAll(tasks);
System.out.println("back in main");
service.shutdown();
service.awaitTermination(20,TimeUnit.SECONDS);
出力:
thread1 coming out of sleep
thread2 coming out of sleep
back in main