Java 关闭钩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19639319/
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
Java shutdown hook
提问by skiwi
I have added the following code to my program:
我已将以下代码添加到我的程序中:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("exit");
}
}){});
I however do not see the message. Additional information: I am running the program from inside the Netbeans IDE on Java 7.
但是,我没有看到该消息。附加信息:我从 Java 7 上的 Netbeans IDE 内部运行该程序。
EDIT: I forgot to add that there is a global Thread that keeps the program alive. I close it by pressing the [x] in Netbeans lower right corner.
编辑:我忘了补充一点,有一个全局线程可以使程序保持活动状态。我通过按 Netbeans 右下角的 [x] 关闭它。
采纳答案by Debojit Saikia
The JVM can shutdown in either an orderly or abrupt manner. A shutdown hook runs for an orderly shutdown: when the last normal
thread terminates, someone calls System.exit
or by other platform specific means (such as typing Ctrl-C).
JVM 可以以有序或突然的方式关闭。关闭钩子为有序关闭而运行:当最后一个normal
线程终止时,有人调用System.exit
或通过其他特定于平台的方式(例如键入 Ctrl-C)。
Shutdown hooks will not run for an abrupt shutdown of the JVM. As you are pressing the [x] in Netbeans lower right corner, this will cause an abrupt shutdown of the JVM and this is why the shutdown hook was not started.
关闭钩子不会在 JVM 突然关闭时运行。当您按下 Netbeans 右下角的 [x] 时,这将导致 JVM 突然关闭,这就是关闭挂钩未启动的原因。
For example :
例如 :
public class ShutdownHook {
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("exit");
}
});
}
public static void main(String[] args) {
ShutdownHook sample = new ShutdownHook();
sample.attachShutDownHook();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
If you run the above code, and let the program complete normally, you will see exit
printed on the console. But if you press [x] (within 3 secs) to close it abruptly, the shutdown hook will not run and there will not be any exit
printed on the console.
如果你运行上面的代码,让程序正常完成,你会exit
在控制台看到printed。但是如果你按 [x](在 3 秒内)突然关闭它,关闭钩子将不会运行,并且exit
控制台上也不会打印任何内容。
回答by libik
I forgot to add that there is a global Thread that keeps the program alive. I close it by pressing the [x] in Netbeans lower right corner.
我忘了补充一点,有一个全局线程可以使程序保持活动状态。我通过按 Netbeans 右下角的 [x] 关闭它。
Well this is it, closing program by "x" in netbeans lower right corner is not regular shut down, it just breaks everything and shut it down.
好了,就是这样,在 netbeans 右下角通过“x”关闭程序并不是常规关闭,它只是破坏了一切并将其关闭。
ShutdownHook works only when the program regulary exits...
ShutdownHook 仅在程序定期退出时才起作用......