通过我们的程序中运行完之后都会进行一些清理工作,比如关闭数据库资源,同步等操作。这时我们的钩子函数addShutdownHook有了用武之地。
1.钩子程序执行时机:
当程序正常退出,系统调用 System.exit方法或虚拟机被关闭时才会执行添加的shutdownHook线程。其中shutdownHook是一个已初始化但并不有启动的线程,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作。
2.用法
Runtime.getRuntime().addShutdownHook(Thread thread)
这里我们需要将一个线程对象传入,作为钩子程序的实现代码。本质上就是在jvm关闭时,执行一个线程。
3.实战
- public class Client{
- public void test1(){
- System.out.println("startting working......");
- Runtime.getRuntime().addShutdownHook(new Thread(){
- public void run() {
- System.out.println("执行钩子线程");
- }
- });
- System.out.println("program endding");
- }
- }
- 执行结果:
- startting working......
- program endding
- 执行钩子线程