监听JVM关闭

使用Runtime的addShutdownHook(thread)方法:

 1         for(int i=0; i<5; i++){
 2             System.out.println(i);
 3         }
 4         
 5         Thread th = new Thread(new Runnable() {
 6             
 7             @Override
 8             public void run() {
 9                 System.out.println("jvm结束了。。。");
10             }
11         });
12         //设置监听线程
13         Runtime.getRuntime().addShutdownHook(th);    

输出结果:

也可使用Runtime.removeShutdownHook(thread)移除监听线程。

posted @ 2014-04-28 22:46  楪夕  阅读(876)  评论(0编辑  收藏  举报