“关闭钩子”(ShutdownHook)是这样一个概念:向虚拟机注册一个线程,当程序退出(Ctrl+C)时虚拟机会启动这个线程,我们可以在这个线程的run()中做一些清除的工作,如:释放数据库连接,关闭文件等.
说明
shutdownhook通常用来在Ctrl+C退出时触发清理工作(多是在后台服务中,这种服务通常是24*7运行的,正常情况下是不退出的),如果能够在程序中显式地确定退出的时机,那么最好是直接在退出前做清理,不用搞得这么复杂。
注册
Runtime.getRuntime().addShutdownHook(Thread t);
注销
Runtime.getRuntime().removeShutdownHook(Thread t);
[例子]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
class TestThread extends Thread { boolean isTerminal = false;
public void run() { while (!isTerminal) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("run sub thread"); } }
public void onTerminal() { isTerminal = true; System.out.println("stop sun sub thread"); } }
public class TestShutdownHook extends Thread { TestThread testThread;
public void addThread(TestThread t) { testThread = t; }
public void run() { System.out.println("This is ShutdownHook"); testThread.onTerminal(); }
public static void main(String[] args) { TestShutdownHook m = new TestShutdownHook(); TestThread t = new TestThread(); t.start(); m.addThread(t); Runtime.getRuntime().addShutdownHook(m); } }
|
运行结果:
1 2 3 4 5 6
| run sub thread run sub thread run sub thread run sub thread This is ShutdownHook stop sun sub thread
|
可以看到:当程序退出时启动了TestThread线程,执行了定义的释放工作。