public class ThreadHookTest {
public static void main(String[] args) {
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================");
}
}
public static void main(String[] args) {
System.out.println("end end");
//增加hook
Runtime.getRuntime().addShutdownHook(new ShutdownHook());
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================”