Runtime.getRuntime().addShutdownHook
来源:互联网 发布:淘宝7天打造爆款 编辑:程序博客网 时间:2024/05/30 04:46
addShutdownHook()是一个终止处理的方法,这个方法会在Java执行环境全部结束时(调用System.exit方法时,或者所有非守护线程都结束时),调用指定线程的start方法(这时候该线程称为shutdown hook),使用该方法可以编写整个程序的终止处理。
示例1:
public class AddShutdownHookTest {
public static void main(String[] args) {
System.out.println("main: BEGIN");
// set shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println(Thread.currentThread().getName()
+ ": Shutdown hook.");
}
});
System.out.println("main: SLEEP..");
// force quit after 3 sec.
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO: handle exception
}
System.out.println("main: EXIT");
// force quit
// System.exit(0);
Runtime.getRuntime().exit(0);
// unreachable code
System.out.println("main: END");
}
}
运行结果:
main: BEGIN
main: SLEEP..
main: EXIT
Thread-0: Shutdown hook.
示例2:
import quicktime.*;
public class QTSessionCheck {
private Thread shutdownHook;
private static QTSessionCheck instance;
private QTSessionCheck() throws QTException {
super();
// init
QTSession.open();
// create shutdown handler
shutdownHook = new Thread() {
public void run() {
QTSession.close();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
private static QTSessionCheck getInstance() throws QTException {
if (instance == null) {
instance = new QTSessionCheck();
}
return instance;
}
/**
* Gets instance.
* If a new one needs to be created, it calls <code>QTSession.open()</code> and creates a shutdown hook to call <code>QTSession.close()</code>
* @throws QTException
*/
public static void check() throws QTException {
getInstance();
}
}
- Runtime.getRuntime().addShutdownHook
- Runtime.getRuntime().addShutdownHook(Thread)
- RunTime.getRunTime().addShutdownHook用法
- RunTime.getRunTime().addShutdownHook用法
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- Runtime.getRuntime().addShutdownHook
- RunTime.getRunTime().addShutdownHook用法
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- RunTime.getRunTime().addShutdownHook用法
- Runtime.getRuntime().addShutdownHook介绍
- RunTime.getRunTime().addShutdownHook用法
- RunTime.getRunTime().addShutdownHook用法
- Runtime.getRuntime().addShutdownHook(Thread)
- RunTime.getRunTime().addShutdownHook用法
- RunTime.getRunTime().addShutdownHook用法
- RunTime.getRunTime().addShutdownHook用法
- RunTime.getRunTime().addShutdownHook用法
- Runtime.getRuntime().addShutdownHook使用
- xiaocainiao!
- 什么是 RSSI RSCP
- DB2查找重复记录SQL
- Java新特性2 -- 泛型
- Could not determine type for: java.util.Boolean, at table:出错的处理
- Runtime.getRuntime().addShutdownHook
- 我的淘宝openAPI之旅
- 把字串转成ASCII
- Web优化的14条法则
- 条款7:为多态基类声明VIRTUAL析构函数
- Web优化的14条法则之一个人看法
- Web优化的14条法则及我们的实际应用
- OpenGL键盘控制图形移动
- Web前端优化的34条法则