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================”
Java中使用ShutdownHook
本文介绍了一个简单的Java程序,展示了如何使用Runtime类的addShutdownHook方法来注册一个关闭钩子。该钩子会在JVM关闭前执行特定的操作,例如清理资源等。程序还创建了一个后台运行的线程用于演示ShutdownHook的触发。
8968

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



