学院首页>网络编程>JSP>为Java应用程序添加退出事件响应

为Java应用程序添加退出事件响应

作者:nankailz… 来源:Java研究组织 添加时间:2006-5-25 21:35:44

  如:下列典型代码

  package untitled14;

  /**
  * This application is to demo how an applcation end
  */
  public class Test {
  public Test() {}
  public static void main(String[] args) {
  Test test1 = new Test();
  //.................
  System.out.println("hello world");
  //Do something before system exit
  System.exit(0);//也可以不写这句代码,让程序自然结束。
  }
  }

  对于简单的应用系统,我们直接可以在System.exit(0)代码执行前,添加需要在应用程序退出前需要完成的工作,如:关闭网络连接,关闭数据库连接等。

  然而,对于比较复杂的多线程应用,线程运行的状态较复杂,我们就很难预料程序何时结束,如何能在应用程序结束事件到来时,处理我们要做的工作呢?这就用到了Java对应用程序的退出的事件出处理机制。

  对当前应用程序对象的获得,Java通过Runtime静态方法:Runtime.getRuntime()通过Runtime的 void addShutdownHook(Thread hook) 法向Java虚拟机注册一个shutdown钩子事件,这样一旦程序结束事件到来时,就运行线程hook,我们在实际应用时候,只要将程序需要完成之前做的一些工作直接通过线程hook来完成。具体演示代码如下:

  /*****************************************************************************
  本程序仅演示,如何在Java应用程序中添加系统退出事件处理机制
  *****************************************************************************/
  package untitled14;
  import java.util.*;
  import java.io.*;

  /**
  * This application is used to demo how to hook the event of an application
  */
  public class Untitled1 {

  public Untitled1() {
  doShutDownWork();
  }

  /***************************************************************************
  * This is the right work that will do before the system shutdown
  * 这里为了演示,为应用程序的退出增加了一个事件处理,
  * 当应用程序退出时候,将程序退出的日期写入 d:\t.log文件
  **************************************************************************/
  private void doShutDownWork() {
  Runtime.getRuntime().addShutdownHook(new Thread() {

   public void run() {
    try {
     FileWriter fw = new FileWriter("d:\\t.log");
     System.out.println("Im going to end");
     fw.write("the application ended! " + (new Date()).toString());
     fw.close();
    }
    catch (IOException ex) {
    }

   }
  });
  }

  /****************************************************
  * 这是程序的入口,仅为演示,方法中的代码无关紧要
  ***************************************************/

  public static void main(String[] args) {
  Untitled1 untitled11 = new Untitled1();
  long s = System.currentTimeMillis();
  for (int i = 0; i < 1000000000; i++) {
   //在这里增添您需要处理代码
  }
  long se = System.currentTimeMillis();
  System.out.println(se - s);
  }
  }

  在上述程序中,我们可以看到通过在程序中增加Runtime.getRuntime().addShutdownHook(new Thread()) 事件监听,捕获系统退出消息到来,然后,执行我们所需要完成工作,从而使我们的程序更健壮!
  • 2005年5月12日
  • 2005年5月10日
  • 2005年3月30日
  • 2005年3月30日
  • 2005年3月30日
  • 2005年3月30日
  • 2005年3月30日
  • 2005年3月29日
  • 2005年3月29日
  • 2005年3月29日
  • 2005年3月29日
  • 2005年3月28日

  • 站内搜索