简体   繁体   English

等待执行后关闭执行器线程

[英]Shutdown Executor thread after awaitConfimation

How to shutdown all threads created with ExecutorService after the 如何在关闭后关闭使用ExecutorService创建的所有线程

executor.awaitTermination(1, TimeUnit.DAYS);

is finished? 完成了吗?

That's the max time threads can work, and if, in some case, any of them does not finish current task, shut it down and start again. 那是线程可以工作的最长时间,如果在某些情况下它们中的任何一个没有完成当前任务,则将其关闭并重新启动。

If awaitTermination returns true, then all the threads have been shutdown. 如果awaitTermination返回true,则所有线程都已关闭。

If awaitTermination returns false, then some of the threads are obviously not responding to interruption*, and apart from exiting the java process, there is not much you can do... 如果awaitTermination返回false,那么某些线程显然不会响应中断*,并且除了退出Java进程外,您无能为力。

*If the tasks run by the threads are yours, make sure they respond to interruption by exiting quickly and awaitTermination will return promptly. *如果线程运行的任务是您的,请确保它们通过快速退出对中断做出响应,并且awaitTermination将立即返回。

There is no easy way to do it. 没有简单的方法可以做到这一点。 You can use a ThreadFactory which will create daemon threads, then run awaitTermination in the main thread, followed by shutdownNow . 您可以使用ThreadFactory来创建守护进程线程,然后在主线程中运行awaitTermination ,然后运行shutdownNow This will (hopefully) shut down the whole JVM, and there is little to nothing better than that in the given situation. (希望)关闭整个JVM,在给定的情况下,没有什么比这更好的了。 Executing System.exit() is an even more drastic measure. 执行System.exit()是一个更为严格的措施。

Note that interrupting or even stopping threads doesn't guarantee that they will actually terminate. 请注意,中断甚至停止线程并不能保证它们会真正终止。

You can call System.exit(1) to stop the application. 您可以调用System.exit(1)停止应用程序。 If you dont want to exit then you should design your tasks so that they react to Thread.interrupt properly, there is no other way. 如果您不想退出,则应该设计任务,以使它们对Thread.interrupt做出正确的反应,没有其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM