创建钩子
JVM 在正常退出时,会启动钩子做一些善后事情。
import java.util.concurrent.TimeUnit;
/**
* 钩子测试
* <p>
*
* @author hyl
* @version v1.0: HookTest.java, v 0.1 2021/1/8 15:22 $
*/
public class HookTest {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("钩子启动");
}));
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在线程以外退出时不会被调用。
以下方式结束无法调用钩子。
jps
5540 HookTest
linux
kill -9 5540
window
taskkill /pid 5540 -f