java中如何停止ExecutorThreadPool的执行?

发布于 2024-08-07 10:33:35 字数 141 浏览 10 评论 0原文

我正在研究 java 中的执行器,以便一次同时运行更多线程。 我有一组可运行对象,并将其分配给执行器。执行器工作正常 一切都很好。但是在池中执行所有任务之后,java程序没有终止,我认为执行器需要一些时间来杀死线程。请任何人帮助我减少执行器执行后所花费的时间所有任务。

I am working on the Executors in java to concurrently run more threads at a time.
I have a set of Runnable Objects and i assign it to the Exceutors.The Executor is working fine
and every thing is fine.But after all the tasks are executed in the pool ,the java program is not terminated,i think the Executor takes some time to kill the threads.please anyone help me to reduce the time taken by the executor after executing all tasks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

池木 2024-08-14 10:33:35

ExecutorService 类有 2 个方法为此: shutdown( )现在关闭()

使用 shutdown() 方法后,可以调用 awaitTermination() 阻塞,直到所有已启动的任务完成。您甚至可以提供超时以防止永远等待。

您可能想单击我提供的其中一些链接。他们直接进入文档,您可以自己阅读这些内容。

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.

压抑⊿情绪 2024-08-14 10:33:35

executor.shutdown() 和awaitTermination(timeout) 不会杀死线程。 (即),如果您的可运行任务位于轮询循环内,则它不会终止该任务。它所做的只是在达到超时时中断其可运行任务。因此,在可运行类的代码中,如果您等待某些条件,您可能需要将条件更改为,

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

这可以确保当线程因 while 循环终止而被中断时任务停止。或者,您可能想捕获中断的异常并设置
catch 块中的 flag=false 来终止线程。

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

您可能还想使用探查器来检查某些线程尚未完成的原因。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文