最近我瞭解了這個Java 1.5的功能,並開發了一個示例代碼來使用它。我的目標是在由於未捕獲的異常而死的時候重新啓動線程。有效使用UncaughtExceptionHandler
public class ThreadManager {
public static void main(String[] args) throws InterruptedException {
startThread();
}
public static void startThread(){
FileReaderThread reader = new FileReaderThread("C:\\Test.txt");
Thread thread = new Thread(reader);
thread.setUncaughtExceptionHandler(new CustomExceptionHandler());
thread.start();
}
}
這裏的文件閱讀器只是包含一個例程來讀取文件和打印內容。我正在模擬一個未捕獲的異常,在該類中使文件名爲null。
然後我的CustomExceptionHandler類如下。
public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
ThreadManager.startThread();
}
}
但是在這裏我觀察到一個問題。在未捕獲的異常之後,線程處於睡眠狀態。我通過使用分析器來驗證它。因此,創建新線程會隨着時間的流逝而填補我的記憶。使system.gc()後跟t = null不起作用。
那麼建議您處理這種情況的最佳方法是什麼?我只是需要一個新的線程,我不希望任何舊的線程更多....
感謝
我剛剛測試了您的代碼,但看不到任何奇怪的行爲,因爲您描述了它(我正在使用JDK6)。 – sfussenegger 2009-10-08 06:42:40
您是否嘗試通過調用'uncaughtException'方法中的't.stop()'來停止線程?儘管Thread.stop()已被棄用。 – Amarghosh 2009-10-08 06:42:49
@sfussenegger:是的..你在功能上看不到任何問題。您只能通過探查器查看它。影響只是在使用的內存。 :) – 2009-10-08 06:45:48