Runtime.getRuntime().addShutdownHook

来源:互联网 发布:淘宝7天打造爆款 编辑:程序博客网 时间:2024/05/30 04:46

addShutdownHook()是一个终止处理的方法,这个方法会在Java执行环境全部结束时(调用System.exit方法时,或者所有非守护线程都结束时),调用指定线程的start方法(这时候该线程称为shutdown hook),使用该方法可以编写整个程序的终止处理。

 

示例1:

public class AddShutdownHookTest {

 public static void main(String[] args) {
  System.out.println("main: BEGIN");

  // set shutdown hook
  Runtime.getRuntime().addShutdownHook(new Thread() {
   public void run() {
    System.out.println(Thread.currentThread().getName()
      + ": Shutdown hook.");
   }
  });

  System.out.println("main: SLEEP..");

  // force quit after 3 sec.
  try {
   Thread.sleep(3000);
  } catch (InterruptedException e) {
   // TODO: handle exception
  }

  System.out.println("main: EXIT");
  // force quit
  // System.exit(0);
  Runtime.getRuntime().exit(0);

  // unreachable code
  System.out.println("main: END");
 }

}

 

运行结果:

main: BEGIN
main: SLEEP..
main: EXIT
Thread-0: Shutdown hook.

 

 

示例2:

import quicktime.*;

public class QTSessionCheck {

    private Thread shutdownHook;
    private static QTSessionCheck instance;

    private QTSessionCheck() throws QTException {
        super();
        // init
        QTSession.open();
        // create shutdown handler
        shutdownHook = new Thread() {

            public void run() {
                QTSession.close();
            }
        };
        Runtime.getRuntime().addShutdownHook(shutdownHook);
    }

    private static QTSessionCheck getInstance() throws QTException {
        if (instance == null) {
            instance = new QTSessionCheck();
        }
        return instance;
    }

    /**
     * Gets instance.
     * If a new one needs to be created, it calls <code>QTSession.open()</code> and creates a shutdown hook to call <code>QTSession.close()</code>
     * @throws QTException
     */
    public static void check() throws QTException {
        getInstance();
    }
}