Runtime.getRuntime().addShutdownHook(new Thread())

来源:互联网 发布:影音先锋替代软件 编辑:程序博客网 时间:2024/06/06 02:15

Runtime.getRuntime()通过Runtime的 void addShutdownHook

(Thread hook) 法向Java虚拟机注册一个shutdown钩子事件,这样一旦程序结束事件到来时,就运行线程hook,我们在实际应

用时候,只要将程序需要完成之前做的一些工作直接通过线程hook来完成。


示例1:

/*****************************************************************************
本程序仅演示,如何在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("I'm going to end");
          fw.write("the application ended! " + (new Date()).toString());
          fw.close();
        }
        catch (IOException ex) {
        }

      }
    });
}

在上述程序中,我们可以看到通过在程序中增加Runtime.getRuntime().addShutdownHook(new Thread()) 事件监听,捕获系统

退出消息到来,然后,执行我们所需要完成工作,从而使我们的程序更健壮!


示例2:

/** * @autoor wangjianqing * @date 2017-06-01 * @modifier */public class Test1 {    public static void main(String[] args) {        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");        Runtime.getRuntime().addShutdownHook(new Thread(context::close));        context.start();        System.exit(0);    }}

上述程序为读取配置文件完后,关闭context。context::close为jdk8语法,代替匿名类。
原创粉丝点击