1、main函数
public static void main(String[] args) {
System.out.println("start");
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("Shutdown start!!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Shutdown end!!!");
}));
System.out.println("exit");
}
2、SpringBoot
原理分析:注册Hook流程
SpringApplication.run(DemoApplication.class, args);
refreshContext(context);
shutdownHook.registerApplicationContext(context);
void registerApplicationContext(ConfigurableApplicationContext context) {
addRuntimeShutdownHookIfNecessary(); //添加Hook
synchronized (SpringApplicationShutdownHook.class) {
assertNotInProgress();
context.addApplicationListener(this.contextCloseListener); //添加监听上下文关闭事件
this.contexts.add(context); //添加需要关闭的上下文
}
}
private void addRuntimeShutdownHookIfNecessary() {
if (this.shutdownHookAdded.compareAndSet(false, true)) {
addRuntimeShutdownHook(); //添加Hook
}
}
void addRuntimeShutdownHook() {
try {
Runtime.getRuntime().addShutdownHook(new Thread(this, "SpringApplicationShutdownHook"));
}
catch (AccessControlException ex) {
// Not allowed in some environments
}
}