开发者

ExecutorService awaitTermination gets stuck

开发者 https://www.devze.com 2023-03-28 05:48 出处:网络
I made a fixed size thread pool with Executors.newFixedThreadPool(2), and I executed 10 Runnable objects. I set breakpoints and traced through the execution. However, fixedSizeThreadPool.awaitTerminat

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

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 awaitTermination. What's wrong?


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

source: javadoc


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 shutdown, if your ExecutorService contains other tasks as well especially scheduled tasks. These would also be affected by a call to shutdown.

0

精彩评论

暂无评论...
验证码 换一张
取 消