WEB开发网
开发学院WEB开发Jsp 如何使用Runtime.addShutdownHook 阅读

如何使用Runtime.addShutdownHook

 2008-01-05 08:28:03 来源:WEB开发网   
核心提示: 以前从未用过 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.最近刚刚接触了一点,如何使用Runtime.addShutdownHook,总结一下,根据 java API, 所谓 shutdown hook 就是已经初始化但尚未开始执行的线程对象,你的清
   以前从未用过 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.
最近刚刚接触了一点,总结一下。

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

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

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

举例如下:

  1. package john2;
  2. /**
  3.  * test shutdown hook
  4.  * All rights released and correctness not guaranteed.
  5.  */
  6. public class ShutdownHook implements Runnable {
  7.   
  8.   public ShutdownHook() {
  9.     // register a shutdown hook for this class.
  10.     // a shutdown hook is an initialzed but not started thread, which will get up and run
  11.     // when the JVM is about to exit. this is used for short clean up tasks.
  12.     Runtime.getRuntime().addShutdownHook(new Thread(this));
  13.     System.out.PRintln(">>> shutdown hook registered");
  14.   }
  15.   
  16.   // this method will be executed of course, since it's a Runnable.
  17.   // tasks should not be light and short, accessing database is alright though.
  18.   public void run() {
  19.     System.out.println("\n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits.");
  20.     this.cleanUp();
  21.     System.out.println(">>> Finished execution: " + ShutdownHook.class.getName() + ".run()");

Tags:如何 使用 Runtime

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接