CTRL-C 如何与 Java 程序配合使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11435533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does CTRL-C work with Java program
提问by user590444
When I press ctrl-cin console in what sequence are application threads stopped and shutdown hooks called?
当我在控制台中按ctrl- 时c,应用程序线程停止并调用关闭挂钩的顺序是什么?
采纳答案by Stephen C
According to the javadocs, the registered shutdown hooks are called in an unspecifiedorder when the JVM starts shutting down; e.g. in response to a CTRL-C.
根据 javadocs,当 JVM 开始关闭时,注册的关闭钩子以未指定的顺序调用;例如响应 CTRL-C。
Application threads are not "stopped" in any well defined way. Indeed, they could continue running up right until the process exits.
应用程序线程不会以任何明确定义的方式“停止”。事实上,它们可以继续运行直到进程退出。
If you want your threads to be shut down in an orderly fashion, you need to do something in a shutdown hook to cause this to happen. For example, a shutdown hook could call Thread.interrupt()
to tell worker threads to stop what they are doing ... and call join()
to make sure that it has happened.
如果您希望您的线程以有序的方式关闭,您需要在关闭挂钩中执行某些操作以使其发生。例如,关闭钩子可以调用Thread.interrupt()
告诉工作线程停止他们正在做的事情......并调用join()
以确保它已经发生。
回答by Martijn Courteaux
I know that you can specify what should happen when Ctrl-C is being hit by adding a shutdown hook. But I'm not sure in what order.
我知道您可以通过添加关闭钩子来指定当按下 Ctrl-C 时应该发生什么。但我不确定按什么顺序。
private static void createShutDownHook()
{
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
@Override
public void run()
{
System.out.println();
System.out.println("Thanks for using the application");
System.out.println("Exiting...");
}
}));
}