Runtime.addShutdownHook添加钩子

来源:互联网 发布:无限极网络电视盒 编辑:程序博客网 时间:2024/06/17 22:05
1 方法含义
void java.lang.Runtime.addShutdownHook(Thread hook) 用来在jvm中增加一个关闭的钩子。
当程序正常退出,系统调用System.exit方法或虚拟机被关闭时才会执行添加的shutdownHook线程。其中shutdownHook是一个已初始化但并不有启动的线程,当jvm关闭时会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作。


2 示例代码
public class TestRuntimeShutdownHook {
public static void main(String[] args) {

Thread shutdownHookOne = new Thread() {
public void run() {
System.out.println("shutdownHook one...");
}
};
Runtime.getRuntime().addShutdownHook(shutdownHookOne);


Runnable threadOne = new Runnable() {

public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread one doing something...");
}
};


Runnable threadTwo = new Thread() {
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread two doing something...");
}
};


threadOne.run();
threadTwo.run();
}
}

输出如下:
thread one doing something...
thread two doing something...
shutdownHook one...


原贴地址:http://kim-miao.iteye.com/blog/1662550
1 0
原创粉丝点击