简体   繁体   English

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");
    }
}){});

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]将其关闭。

The JVM can shutdown in either an orderly or abrupt manner. JVM可以有序或突然关闭。 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). 关闭挂钩会运行以有序关闭:最后一个normal线程终止时,有人调用System.exit或通过其他平台特定的方式(例如键入Ctrl-C)。

Shutdown hooks will not run for an abrupt shutdown of the JVM. 关机挂钩不会在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. 在Netbeans的右下角按[x]时,这将导致JVM突然关闭,这就是为什么未启动shutdown钩子的原因。

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. 如果运行上面的代码,并让程序正常完成,您将看到控制台上显示exit 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. 但是,如果按[x](在3秒钟内)突然将其关闭,则关闭挂钩将不会运行,并且控制台上将不会打印任何exit

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仅在程序定期退出时才起作用。

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

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