有时候会有需求:想要监控主程序结束。在主程序结束的时候,执行一些代码。
可以用Runtime中的addShutdownHook
package com.thread;
public class T1_Hook {
public static void main(String[] args) {
System.out.println("start");
//加钩子:主线程结束走该线程
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
super.run();
System.out.println("============主程序结束================");
}
});
System.out.println("end");
//其他的线程:模拟springboot中,主线程跑起来后,其中的各种线程
new Thread(()->{
int i = 0;
while (i < 10) {
System.out.println(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
感谢此文
为主程序增加Hook,监控主线程的退出_日志的博客-CSDN博客
看下Runtime的源码:
public class Runtime {
//单例模式
private static Runtime currentRuntime = new Runtime();
public static Runtime getRuntime() {
return currentRuntime;
}
//不让别人实例化
private Runtime() {}
...
}
Runtime使用了单例模式
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)