ExecutorService awaitTermination gets stuck

I made a fixed size thread pool with , and I executed 10 objects. I set breakpoints and traced through the execution. However, does not allow me to continue even though all the tasks are done. Executors.newFixedThreadPool(2)RunnablefixedSizeThreadPool.awaitTermination()

Basically:

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
for (int i = 0; i < 10; ++i) {
    fixedSizeThreadPool.execute(myRunables[i]);
}
try {
    fixedSizeThreadPool.awaitTermination(timeout, timeoutUnits);
} catch (Exception e) { }
System.out.println("done!");

But this always gets stuck on . What's wrong?awaitTermination


答案 1

As Peter pointed out, must be called first.shutdown()

source: javadoc


答案 2

You could also use ExecutorService#invokeAll. It blocks until all tasks are done or the timeout is reached. It's a little cleaner than using , if your ExecutorService contains other tasks as well especially scheduled tasks. These would also be affected by a call to .shutdownshutdown