当JVM正常或突然关闭时,关闭挂钩可用于执行清理资源或保存状态。 执行干净资源意味着关闭日志文件,发送一些警报或其他内容。 因此,如果要在JVM关闭之前执行某些代码,请使用关闭挂钩(shutdown hook)。
JVM什么时候关闭?JVM在以下情况下关闭:
用户在命令提示符下按ctrl + c
调用System.exit(int)方法
用户注销计算机。
用户关闭计算机等
addShutdownHook(Thread hook)方法Runtime类的addShutdownHook()方法用于向虚拟机注册线程。
语法如下:
public void addShutdownHook(Thread hook){}
可以通过调用静态工厂方法getRuntime()来获取Runtime类的对象。 例如:
Runtime r = Runtime.getRuntime();
工厂方法返回类实例的方法称为工厂方法。
Shutdown Hook的简单示例
package com.yiibai; class MyThread extends Thread{ public void run(){ System.out.println("shut down hook task completed.."); } } public class TestShutdown1{ public static void main(String[] args)throws Exception { Runtime r=Runtime.getRuntime(); r.addShutdownHook(new MyThread()); System.out.println("Now main sleeping... press ctrl+c to exit"); try{Thread.sleep(3000);}catch (Exception e) {} } }
执行上面示例代码,得到以下结果:
Now main sleeping... press ctrl+c to exit shut down hook task completed.. Process finished with exit code 0
注意: 可以通过调用Runtime类的halt(int)方法来停止关闭序列。
使用匿名类的Shutdown Hook示例:
package com.yiibai; public class TestShutdown2{ public static void main(String[] args)throws Exception { Runtime r=Runtime.getRuntime(); r.addShutdownHook(new Thread(){ public void run(){ System.out.println("shut down hook task completed.."); } } ); System.out.println("Now main sleeping... press ctrl+c to exit"); try{Thread.sleep(3000);}catch (Exception e) {} } }
执行上面示例代码,得到以下结果:
Now main sleeping... press ctrl+c to exit shut down hook task completed.. Process finished with exit code 0
¥ 我要打赏 纠错/补充 收藏