Runtime.getRuntime().addShutdownHook

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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值