一.Runtime.addShutdownHook理解 java
在看別人的代碼時,發現其中有這個方法,便順便梳理一下。 jvm
void java.lang.Runtime.addShutdownHook(Thread hook) spa
該方法用來在jvm中增長一個關閉的鉤子。當程序正常退出,系統調用 System.exit方法或虛擬機被關閉時纔會執行添加的shutdownHook線程。其中shutdownHook是一個已初始化但並不有啓動的線 程,當jvm關閉的時候,會執行系統中已經設置的全部經過方法addShutdownHook添加的鉤子,當系統執行完這些鉤子後,jvm纔會關閉。因此 可經過這些鉤子在jvm關閉的時候進行內存清理、資源回收等工做。 線程
二.示例代碼 內存
Java代碼
- public class TestRuntimeShutdownHook {
- public static void main(String[] args) {
-
- Thread shutdownHookOne = new Thread() {
- public void run() {
- System.out.println("shutdownHook one...");
- }
- };
- Runtime.getRuntime().addShutdownHook(shutdownHookOne);
-
- Runnable threadOne = new Runnable() {
- public void run() {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("thread one doing something...");
- }
- };
-
- Runnable threadTwo = new Thread() {
- public void run() {
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("thread two doing something...");
- }
- };
-
- threadOne.run();
- threadTwo.run();
- }
- }
輸出以下: 資源
Java代碼
- thread one doing something...
- thread two doing something...
-
- shutdownHook one...