111111
精灵王
精灵王
  • 注册日期2010-12-08
  • 发帖数640
  • QQ
  • 火币1103枚
  • 粉丝120
  • 关注75
  • 社区明星
阅读:2830回复:0

为你的Java应用程式添加退出事件处理-JSP教程,Java技巧及代码

楼主#
更多 发布于:2011-01-08 20:45
一个完整的java应用程式,通常至少要有一个应用程式的结束点。对于一般程式来说,系统研发者根据需要和个人的偏好,会在程式结束位置,通过添加system.exit(0),或system.out(-1),来结束程式,或不加这些指令,让程式自然运行到结束。
如:下列典型代码
[pre]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);//也能不写这句代码,让程式自然结束。      }}[/pre]

对于简单的应用系统,我们直接能在system.exit(0)代码执行前,添加需要在应用程式退出前需要完成的工作,如:关闭网络连接,关闭数据库连接等。
然而,对于比较复杂的多线程应用,线程运行的状态较复杂,我们就非常难预料程式何时结束,怎么能在应用程式结束事件到来时,处理我们要做的工作呢?这就用到了java对应用程式的退出的事件出处理机制。
对当前应用程式对象的获得,java通过runtime静态方法:runtime.getruntime()通过runtime的 void addshutdownhook(thread hook) 法向java虚拟机注册一个shutdown钩子事件,这样一旦程式结束事件到来时,就运行线程hook,我们在实际应用时候,只要将程式需要完成之前做的一些工作直接通过线程hook来完成。具体演示代码如下:
[pre]/*****************************************************************************本程式仅演示,怎么在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);  }}[/pre]

在上述程式中,我们能看到通过在程式中增加runtime.getruntime().addshutdownhook(new thread()) 事件监听,捕捉系统退出消息到来,然后,执行我们所需要完成工作,从而使我们的程式更健壮!


更多黑客技术 黑客软件 计算机技术 编程技术 网站技术 qq技术 IT新闻 黑客基地 请访问 灯火安全联盟  灯火黑客 www.hack8888.com/bbs

喜欢0 评分0
游客

返回顶部