Java Runtime removeShutdownHook()方法

java.lang.Runtime.removeShutdownHook(Thread hook) 方法去注册一个以前注册的虚拟机关闭挂钩。

1 语法

public boolean removeShutdownHook(Thread hook)

2 参数

hook : 除去的钩

3 返回值

如果指定的钩先前已注册并已成功取消注册,此方法返回true,否则返回false。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Runtime removeShutdownHook()方法
 */
public class RuntimeDemo {

   // a class that extends thread that is to be called when program is exiting
   static class Message extends Thread {

      public void run() {
         System.out.println("Bye.");
      }
   }

   public static void main(String[] args) {
      try {
         Message p = new Message();
         // register Message as shutdown hook
         Runtime.getRuntime().addShutdownHook(p);

         // print the state of the program
         System.out.println("Program is starting...");

         // cause thread to sleep for 3 seconds
         System.out.println("Waiting for 3 seconds...");
         Thread.sleep(3000);

         // remove the hook
         Runtime.getRuntime().removeShutdownHook(p);

         // print that the program is closing 
         System.out.println("Program is closing...");


      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

输出结果为:

Program is starting...
Waiting for 3 seconds...
Program is closing...

 

热门文章

优秀文章