java.lang.Runtime.removeShutdownHook(Thread hook)方法範例


java.lang.Runtime.removeShutdownHook(Thread hook) 方法去註冊一個以前註冊的虛擬機器關閉掛鉤。

宣告

以下是java.lang.Runtime.removeShutdownHook()方法的宣告

public boolean removeShutdownHook(Thread hook)

引數

  • hook -- 除去的鉤

返回值

如果指定的鉤先前已註冊並已成功取消註冊,此方法返回true,否則返回false。

異常

  • IllegalStateException -- 如果虛擬機器已處於關閉的過程中

  • SecurityException -- 如果安全管理器存在並且它拒絕RuntimePermission(“shutdownHooks”)

例子

下面的例子顯示lang.Runtime.removeShutdownHook()方法的使用。

package com.yiibai;

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...