Java提供注册钩子线程,在JVM进程关闭以前,会自动执行这个钩子线程。ide
运用这个技巧,能够再JVM关闭以前,释放一些系统资源。函数
这个功能利用的是Runtime类来实现。spa
public class Hook { public static void main(String args[]){ System.out.println("程序开始执行"); try{ Thread.sleep(100); } catch(Exception ex){ } Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("执行钩子函数 -- " + 1); } }); Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("执行钩子函数 -- " + 2); } }); Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("执行钩子函数 -- " + 3); } }); Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { System.out.println("执行钩子函数 -- " + 4); } }); System.out.println("程序执行完毕,退出main"); } }
输出线程
能够看到,执行顺序和注册顺序是不一致的。通常也不会 注册多个钩子函数。code
程序开始执行 程序执行完毕,退出main 执行钩子函数 -- 2 执行钩子函数 -- 3 执行钩子函数 -- 4 执行钩子函数 -- 1
同时,还提供了移除钩子函数的功能blog
public boolean removeShutdownHook(Thread hook)