java中如何停止ExecutorThreadPool的执行?
我正在研究 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.
executor.shutdown() 和awaitTermination(timeout) 不会杀死线程。 (即),如果您的可运行任务位于轮询循环内,则它不会终止该任务。它所做的只是在达到超时时中断其可运行任务。因此,在可运行类的代码中,如果您等待某些条件,您可能需要将条件更改为,
这可以确保当线程因 while 循环终止而被中断时任务停止。或者,您可能想捕获中断的异常并设置
catch 块中的 flag=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,
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.
You might also want to use a profiler to examine why some threads have not proceeded to completion.