Java Runtime removeShutdownHook() 方法



描述

Java Runtime removeShutdownHook(Thread hook) 方法登出先前註冊的虛擬機器關閉鉤子。

宣告

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

public boolean removeShutdownHook(Thread hook)

引數

hook − 要移除的鉤子

返回值

如果先前已註冊指定鉤子併成功登出,則此方法返回true;否則返回false

異常

  • IllegalStateException − 如果虛擬機器已在關閉過程中

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

示例:從執行緒物件中移除關閉鉤子

以下示例顯示了 Java Runtime addShutdownHook() 方法的使用。在這個程式中,我們建立了一個靜態內部類 Message,它擴充套件了 Thread。在 main 方法中,我們使用 addShutdownHook() 方法用一個新的 Message 物件註冊了一個關閉鉤子。然後我們將系統休眠 3 秒。

現在使用 removeShutdownHook() 方法移除關閉鉤子,然後列印一條關閉訊息。由於關閉鉤子是用 Message 物件註冊的,因此當程式退出時,它的 run 方法應該被呼叫,但是由於 removeShutdownHook() 移除了關閉鉤子,“再見”訊息在程式退出時不會列印到控制檯。

package com.tutorialspoint;

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...
java_lang_runtime.htm
廣告
© . All rights reserved.