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.