主要用来在JVM关闭前,执行一些自定义操作。
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(t6);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
private static Thread t1 = new Thread() {
public void run() {
System.out.println("thread1...");
}
};
private static Thread t2 = new Thread() {
public void run() {
System.out.println("thread2...");
}
};
private static Thread t3 = new Thread() {
public void run() {
System.out.println("thread3...");
}
};
private static Thread t4 = new Thread() {
public void run() {
System.out.println("thread4...");
}
};
private static Thread t5 = new Thread() {
public void run() {
System.out.println("thread5...");
}
};
private static Thread t6 = new Thread() {
public void run() {
System.out.println("thread6...");
}
};
}执行结果:
thread2...
thread1...
thread3...
thread4...
thread5...
thread6... // thread6总在最后执行
本文介绍如何在Java中通过自定义线程实现JVM关闭前执行特定操作,通过创建多个线程并使用Runtime类的addShutdownHook方法来确保在JVM关闭时执行一系列定制任务。
193

被折叠的 条评论
为什么被折叠?



