关于addShutdownHook()

来源:互联网 发布:c语言中! 编辑:程序博客网 时间:2024/05/18 03:48

 

执行以下代码:

Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
           System.out.println("shutting down");
      }
});

System.out.println("1");
System.out.println("2");

结果显示:

1
2
shutting down


由此可见shutdown hook 就是已经初始化但尚未开始执行的线程对象。在Runtime 注册后,如果 jvm 要停止前,这些 shutdown hook 便开始执行。

先执行了:
System.out.println("1");
System.out.println("2");
    JVM将关闭的时候才开始执行:

Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
           System.out.println("shutting down");
      }
});

addShutDownHook 的作用就是:在你的程序结束前,执行一些清理工作,尤其是没有UI的程序。
由API: There're couple of cases that JVM will exit, according to the Java api doc. typically:

1. method called: System.exit(int)
2. ctrl-C pressed on the console.
3. the last non-daemon thread exits.
4. user logoff or system shutdown.

原创粉丝点击