Java.lang.Runtime.removeShutdownHook() 方法
描述
java.lang.Runtime.removeShutdownHook(Thread hook) 方法取消注册之前注册的虚拟机关闭挂钩。
声明
以下是 java.lang.Runtime.removeShutdownHook() 方法的声明。
public boolean removeShutdownHook(Thread hook)
参数
hook − the hook to remove
返回值
如果指定的挂钩先前已注册并成功取消注册,则此方法返回 true,否则返回 false。
异常
IllegalStateException − 如果虚拟机已经在关闭过程中
SecurityException − 如果存在安全管理器并且它拒绝 RuntimePermission("shutdownHooks")
示例
下面的例子展示了 lang.Runtime.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...