【Java】 对JVM添加ShutdownHook管理停止时的操作

对JVM添加ShutdownHook管理停止时的操作

JVM准备停止时,添加ShutdownHook监听状态,可处理一些对象的生命周期

简单例子

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
public class Demo {

public static void main(String[] args) throws IOException {
System.out.println("Start.");

// adding hook
Runtime.getRuntime().addShutdownHook(new Thread(new Hook(),"hook"));
Runtime.getRuntime().addShutdownHook(new Thread(new Hook2(),"hook2"));

// imitate do something...
System.in.read();

System.out.println("Shutdown.");
}


static class Hook implements Runnable{
@Override
public void run() {
// 当jvm准备停止时执行此hook
System.out.println(Thread.currentThread().getName()+": Hook Running.");
}
}

static class Hook2 implements Runnable{
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 当jvm准备停止时执行此hook
System.out.println(Thread.currentThread().getName()+": Hook Running.");
}
}
}