RunTime.getRunTime().addShutdownHook用法
Posted on 2011-07-04 17:36 瘋狂 閱讀(1782) 評(píng)論(0) 編輯 收藏 所屬分類: java今天在閱讀Tomcat源碼的時(shí)候,catalina這個(gè)類中使用了下邊的代碼,不是很了解,所以google了一下,然后測(cè)試下方法,Tomcat中的相關(guān)代碼如下:
Runtime.getRuntime().addShutdownHook(shutdownHook);
這個(gè)方法的含義說(shuō)明:
這個(gè)方法的意思就是在jvm中增加一個(gè)關(guān)閉的鉤子,當(dāng)jvm關(guān)閉的時(shí)候,會(huì)執(zhí)行系統(tǒng)中已經(jīng)設(shè)置的所有通過(guò)方法addShutdownHook添加的鉤子,當(dāng)系統(tǒng)執(zhí)行完這些鉤子后,jvm才會(huì)關(guān)閉。所以這些鉤子可以在jvm關(guān)閉的時(shí)候進(jìn)行內(nèi)存清理、對(duì)象銷毀等操作。
一、編寫個(gè)測(cè)試類
package com.test.hook;
public class TestShutdownHook {
/**
* @param args
*/
public static void main(String[] args) {
// 定義線程1
Thread thread1 = new Thread() {
public void run() {
System.out.println("thread1...");
}
};
// 定義線程2
Thread thread2 = new Thread() {
public void run() {
System.out.println("thread2...");
}
};
// 定義關(guān)閉線程
Thread shutdownThread = new Thread() {
public void run() {
System.out.println("shutdownThread...");
}
};
// jvm關(guān)閉的時(shí)候先執(zhí)行該線程鉤子
Runtime.getRuntime().addShutdownHook(shutdownThread);
thread1.start();
thread2.start();
}
}
打印結(jié)果:
thread2...
thread1...
shutdownThread...
或者:
thread2...
thread1...
shutdownThread...
結(jié)論:
無(wú)論是先打印thread1還是thread2,shutdownThread 線程都是最后執(zhí)行的(因?yàn)檫@個(gè)線程是在jvm執(zhí)行關(guān)閉前才會(huì)執(zhí)行)。
轉(zhuǎn)載自:http://blog.csdn.net/wgw335363240/article/details/5854402