Java关闭钩子 [英] Java shutdown hook
问题描述
我已将以下代码添加到我的程序中:
I have added the following code to my program:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("exit");
}
}){});
但是我看不到这条消息。附加信息:我正在Netbeans IDE中运行程序。
I however do not see the message. Additional information: I am running the program from inside Netbeans IDE.
编辑:我忘了添加一个全局线程来保持程序活着。我按下Netbeans右下角的[x]来关闭它。
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.
推荐答案
JVM可以有序或突然关闭方式。关闭挂钩运行以便有序关闭:当最后一个正常
线程终止时,有人调用 System.exit
或其他特定于平台的方法(例如键入Ctrl-C)。
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的突然关闭而运行。当你按下Netbeans右下角的[x]时,这将导致JVM突然关闭,这就是没有启动关闭钩子的原因。
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.
For示例:
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();
}
}
}
如果您运行上面的代码,并让程序正常完成,您将在控制台上看到 exit
。但是如果你按[x](在3秒内)突然关闭它,关机挂钩将不会运行,并且控制台上不会打印任何退出
。
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.
这篇关于Java关闭钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!