服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

如何使用runtime.addshutdownhook

    以前从未用过 runtime.addshutdownhook(thread), 也不知道什么是 shutdown hook.
最近刚刚接触了一点,总结一下。

根据 java api, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象。在
runtime 注册后,如果 jvm 要停止前,这些 shutdown hook 便开始执行。

有什么用呢?就是在你的程序结束前,执行一些清理工作,尤其是没有用户界面的程序。

很明显,这些 shutdown hook 都是些线程对象,因此,你的清理工作要写在 run() 里。
根据 java api,你的清理工作不能太重了,要尽快结束。但仍然可以对数据库进行操作。

举例如下:

  1. package john2;
  2. /**
  3.  * test shutdown hook
  4.  * all rights released and correctness not guaranteed.
  5.  */
  6. public class shutdownhook implements runnable {
  7.     
  8.     public shutdownhook() {
  9.         // register a shutdown hook for this class.
  10.         // a shutdown hook is an initialzed but not started thread, which will get up and run
  11.         // when the jvm is about to exit. this is used for short clean up tasks.
  12.         runtime.getruntime().addshutdownhook(new thread(this));
  13.         system.out.println(">>> shutdown hook registered");
  14.     }
  15.     
  16.     // this method will be executed of course, since it's a runnable.
  17.     // tasks should not be light and short, accessing database is alright though.
  18.     public void run() {
  19.         system.out.println("/n>>> about to execute: " + shutdownhook.class.getname() + ".run() to clean up before jvm exits.");
  20.         this.cleanup();
  21.         system.out.println(">>> finished execution: " + shutdownhook.class.getname() + ".run()");
  22.     }
  23.     
  24.         // (-: a very simple task to execute
  25.     private void cleanup() {
  26.         for(int i=0; i < 7; i++) {
  27.             system.out.println(i);
  28.         }
  29.     }
  30.     /**
  31.      * there're couple of cases that jvm will exit, according to the java api doc.
  32.      * typically:
  33.      * 1. method called: system.exit(int)
  34.      * 2. ctrl-c pressed on the console.
  35.      * 3. the last non-daemon thread exits.
  36.      * 4. user logoff or system shutdown.
  37.      * @param args
  38.      */
  39.     public static void main(string[] args) {
  40.         
  41.         new shutdownhook();
  42.         
  43.         system.out.println(">>> sleeping for 5 seconds, try ctrl-c now if you like.");
  44.         
  45.         try {
  46.             thread.sleep(5000);     // (-: give u the time to try ctrl-c
  47.         } catch (interruptedexception ie) { 
  48.             ie.printstacktrace(); 
  49.         }
  50.         
  51.         system.out.println(">>> slept for 10 seconds and the main thread exited.");
  52.     }
  53. }


参考资料:
1. java api documentation
2. http://java.sun.com/j2se/1.3/docs/guide/lang/hook-design.html

扫描关注微信公众号