位置:首页 > Java技术 > java.lang > java.lang.Runtime.removeShutdownHook(Thread hook)方法实例

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