在程序异常退出或者kill的时候, 发邮件通知管理员,主动通知其他调用程序,释放资源等操作
但是用kill -9是不行的,这也是我们平时结束程序禁止用kill -9的原因
import java.util.Optional;
public class Demo {
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("The application will be exit.");
notifyAndRelease();
}));
// 模拟异常退出
// int i = 0;
while(true){
try {
Optional.of("I am working...").ifPresent(System.out::println);
Thread.sleep(1_000);
} catch (InterruptedException e) {
// ignore
}
// i++;
// if(i > 10){
// throw new RuntimeException("error");
// }
}
}
private static void notifyAndRelease(){
System.out.println("发邮件通知别人");
System.out.println("主动通知其他调用程序");
System.out.println("释放资源");
}
}