场景:如果希望,在jvm关闭时,先执行内存回收,对象销毁,先处理其他非守护线程,不处理某个线程,等到最后关闭jvm时才处理此线程
用法:定义一个线程方法,在jvm关闭之前执行此方法
代码实例:
public static void main(String[] args) {
Thread hookThread = new Thread() {
public void run() {
System.out.println("Run hookThread...");
}
};
Runtime.getRuntime().addShutdownHook(hookThread);
Runnable task1 = new Runnable() {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Run task1...gogogo");
}
};
Runnable task2 = new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Run task2...gogogo");
}
};
task1.run();
task2.run();
}
结果:
Run task1...gogogo
Run task2...gogogo
Run hookThread...