以前從未用過 Runtime.addShutdownHook(Thread), 也不知道什么是 shutdown hook.
最近剛剛接觸了一點(diǎn),總結(jié)一下。

根據(jù) Java API, 所謂 shutdown hook 就是已經(jīng)初始化但尚未開始執(zhí)行的線程對象。在
Runtime 注冊后,如果 jvm 要停止前,這些 shutdown hook 便開始執(zhí)行。

有什么用呢?就是在你的程序結(jié)束前,執(zhí)行一些清理工作,尤其是沒有用戶界面的程序。

很明顯,這些 shutdown hook 都是些線程對象,因此,你的清理工作要寫在 run() 里。
根據(jù) Java API,你的清理工作不能太重了,要盡快結(jié)束。但仍然可以對數(shù)據(jù)庫進(jìn)行操作。


舉例如下:

 


public class ShutdownHook implements Runnable 
     
    
public ShutdownHook() 
        
// register a shutdown hook for this class.
        
// a shutdown hook is an initialzed but not started thread, which will get up and run
        
// when the JVM is about to exit. this is used for short clean up tasks.
        Runtime.getRuntime().addShutdownHook(new Thread(this)); 
        System.out.println(
">>> shutdown hook registered"); 
    }
 
     
    
// this method will be executed of course, since it's a Runnable.
    
// tasks should not be light and short, accessing database is alright though.
    public void run() 
        System.out.println(
"\n>>> About to execute: " + ShutdownHook.class.getName() + ".run() to clean up before JVM exits."); 
        
this.cleanUp(); 
        System.out.println(
">>> Finished execution: " + ShutdownHook.class.getName() + ".run()"); 
    }
 
     
        
// (-: a very simple task to execute
    private void cleanUp() 
        
for(int i=0; i < 7; i++
            System.out.println(i); 
        }
 
    }
 

    
/**
     * there're couple of cases that JVM will exit, according to the Java api doc.
     * typically:
     * 1. method called: System.exit(int)
     * 2. ctrl-C pressed on the console.
     * 3. the last non-daemon thread exits.
     * 4. user logoff or system shutdown.
     * 
@param args
     
*/

    
public static void main(String[] args) 
         
        
new ShutdownHook(); 
         
        System.out.println(
">>> Sleeping for 5 seconds, try ctrl-C now if you like."); 
         
        
try 
            Thread.sleep(
5000);     // (-: give u the time to try ctrl-C
        }
 catch (InterruptedException ie) {  
            ie.printStackTrace();  
        }
 
         
        System.out.println(
">>> Slept for 10 seconds and the main thread exited."); 
    }
 

}
 


結(jié)果:
>>> shutdown hook registered
>>> Sleeping for 5 seconds, try ctrl-C now if you like.
>>> Slept for 10 seconds and the main thread exited.

>>> About to execute: ShutdownHook.run() to clean up before JVM exits.
0
1
2
3
4
5
6
>>> Finished execution: ShutdownHook.run()