How to stop the execution of Executor ThreadPool in java?

[亡魂溺海] 提交于 2019-11-27 20:31:54

The ExecutorService class has 2 methods just for this: shutdown() and shutdownNow().

After using the shutdown() method, you can call awaitTermination() to block until all of the started tasks have completed. You can even provide a timeout to prevent waiting forever.

You might want to click on some of these links that I'm providing. They go straight to the docs where you can readup on this stuff yourself.

Jagadish

executor.shutdown() with awaitTermination(timeout) does not kill threads. (ie), if your runnable task is inside a polling loop, it does not kill the task. All it does is to interrupt its runnable tasks when the timeout is reached. So, in the code for your runnable class, if you wait on some condition, you may want to change the condition as,

while (flagcondition && !Thread.currentThread().isInterrupted()) {}

This ensures that the task stops when the thread is interrupted as the while loop terminates. Alternately, you might want to catch the interrupted exception and set flag=false in the catch block to terminate the thread.

try {
    // do some stuff and perform a wait that might throw an InterruptedException
} catch (InterruptedException e) {
    flagcondition = false;
}

You might also want to use a profiler to examine why some threads have not proceeded to completion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!