监听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);    

输出结果:

监听JVM关闭

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

你可能感兴趣的:(jvm)