如何使用Runtime.addShutdownHook

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

以前从未用过 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.

最近刚刚接触了一点,总结一下。

根据 Java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象。在

Runtime 注册后,假如 jvm 要停止前,这些 shutdown hook 便开始执行。

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

很明显,这些 shutdown hook 都是些线程对象,因此,你的清理工作要写在 run() 里。

根据 Java API,你的清理工作不能太重了,要尽快结束。但仍然可以对数据库进行操作。

举例如下:

package john2;

/**

* test shutdown hook

* All rights released and correctness not guaranteed.

*/

public class ShutdownHook implements Runnable {

public ShutdownHook() {

// 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(new Thread(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.

public void run() {

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()");

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航