为程序加上关闭钩子(ShutdownHook)

zjun Lv4

关闭钩子”(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
/**
* 在这个线程中实现程序退出前的清理工作
*
* @author Administrator
*
*/
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");
}
}

/**
* ShutdownDownHook测试类
*
* @author Administrator
*
*/
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线程,执行了定义的释放工作

  • 标题: 为程序加上关闭钩子(ShutdownHook)
  • 作者: zjun
  • 创建于 : 2006-03-12 23:38:00
  • 更新于 : 2023-11-30 14:25:20
  • 链接: https://zjun.site/2006/03/5cc83b7cc575.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
为程序加上关闭钩子(ShutdownHook)