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