Chinaunix首页 | 论坛 | 博客
  • 博客访问: 543514
  • 博文数量: 625
  • 博客积分: 40000
  • 博客等级: 大将
  • 技术积分: 4745
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-17 15:46
文章分类

全部博文(625)

文章存档

2011年(1)

2008年(624)

我的朋友

分类:

2008-10-17 15:47:10

  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. }

--------------------next---------------------

阅读(346) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~