java Runtime ShutDownHook说明
应用:程序正常执行完毕、异常退出、强制退出(system.exit())时调用预定义的操作
**************************
相关类
Runtime
public class Runtime {
********
构造函数
private Runtime() {}
********
相关方法
public static Runtime getRuntime() {
return currentRuntime;
}
public void addShutdownHook(Thread hook) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new RuntimePermission("shutdownHooks"));
}
ApplicationShutdownHooks.add(hook);
}
**************************
示例:System.exit(int status)
public class Test {
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("shutdown hook:"+System.currentTimeMillis());
}));
System.out.println(Thread.currentThread().getName()+"开始运行:"+System.currentTimeMillis());
System.exit(0);
System.out.println(Thread.currentThread().getName()+"运行结束:"+System.currentTimeMillis());
try{
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
*******************
相关输出
main开始运行:1584606724420
shutdown hook:1584606724438
**************************
示例:程序正常退出
public class Test {
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("shutdown hook:"+System.currentTimeMillis());
}));
System.out.println(Thread.currentThread().getName()+"开始运行:"+System.currentTimeMillis());
System.out.println(10/20);
System.out.println(Thread.currentThread().getName()+"运行结束:"+System.currentTimeMillis());
try{
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
*******************
相关输出
main开始运行:1584606937250
0
main运行结束:1584606937266
shutdown hook:1584606938266
**************************
示例:程序异常退出
public class Test {
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("shutdown hook:"+System.currentTimeMillis());
}));
System.out.println(Thread.currentThread().getName()+"开始运行:"+System.currentTimeMillis());
System.out.println(10/0);
System.out.println(Thread.currentThread().getName()+"运行结束:"+System.currentTimeMillis());
try{
Thread.sleep(1000);
}catch (Exception e){
e.printStackTrace();
}
}
}
*******************
相关输出
main开始运行:1584607007657
shutdown hook:1584607007676
Exception in thread "main" java.lang.ArithmeticException: / by zero
at lifecycle.Test.main(Test.java:11)