如何使用Runtime.addShutdownHook

以前从未用过 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.
最近刚刚接触了一点,总结一下。

根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象。在
Runtime 注册后,如果 jvm 要停止前,这些 shutdown hook 便开始执行。

有什么用呢?就是在你的程序结束前,执行一些清理工作,尤其是没有用户界面的程序。

很明显,这些 shutdown hook 都是些线程对象,因此,你的清理工作要写在 run() 里。
根据 Java API,你的清理工作不能太重了,要尽快结束。但仍然可以对数据库进行操作。

举例如下:



packagejohn2;

/**
* test shutdown hook
* All rights released and correctness not guaranteed.
*/
publicclassShutdownHookimplementsRunnable{

publicShutdownHook() {
// register a shutdown hook for this class.
// a shutdown hook is an initialzed but not started thread, which will get up and run
// when the JVM is about to exit. this is used for short clean up tasks.
Runtime.getRuntime().addShutdownHook(newThread(this));
System.out.println(">>> shutdown hook registered");
}

// this method will be executed of course, since it's a Runnable.
// tasks should not be light and short, accessing database is alright though.
publicvoidrun() {
System.out.println("/n>>> About to execute: " ShutdownHook.class.getName() ".run() to clean up before JVM exits.");
this.cleanUp();
System.out.println(">>> Finished execution: " ShutdownHook.class.getName() ".run()");
}

// (-: a very simple task to execute
**voidcleanUp() {
for(inti=0; i < 7; i) {
System.out.println(i);
}
}

/**
* there're couple of cases that JVM will exit, according to the Java api doc.
* typically:
* 1. method called: System.exit(int)
* 2. ctrl-C pressed on the console.
* 3. the last non-daemon thread exits.
* 4. user logoff or system shutdown.
* @param args
*/
publicstaticvoidmain(String[] args) {

newShutdownHook();

System.out.println(">>> Sleeping for 5 seconds, try ctrl-C now if you like.");

try{
Thread.sleep(5000); // (-: give u the time to try ctrl-C
}catch(InterruptedExceptionie) {
ie.printStackTrace();
}

System.out.println(">>> Slept for 10 seconds and the main thread exited.");
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值