为主程序增加Hook,监控主线程的退出

来源:互联网 发布:linux 查看网卡ip 编辑:程序博客网 时间:2024/05/29 17:59
public class ThreadHookTest {


public static void main(String[] args) {

System.out.println("end end");

//增加hook

Runtime.getRuntime().addShutdownHook(new ShutdownHook());


System.out.println("main end");
Thread t = new Thread(new Runnable(){
@Override
public void run() {
int i=0;
while(i<100){
System.out.println(i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}

static class ShutdownHook extends Thread{


@Override
public void run() {
System.out.println("============shutdown================");
}

}

}

当线程 t 执行完毕后,调用ShutdownHook ,打印“============shutdown================”


原创粉丝点击