如果在java中定義了如下的類,希望在多線程環境下,捕獲異常
static class myRun implements Runnable { @Override public void run() { System.out.println("myRun.run()"); throw new RuntimeException(); } }
那麼通過如下兩種方式,是不能在調用這兩個線程的程式中,捕獲到異常的。
try { new Thread(new myRun()).start(); } catch (Exception e) { // TODO: handle exception System.out.println("caught exception in main"); } try { Executors.newCachedThreadPool().execute(new myRun()); } catch (Exception e) { // TODO: handle exception System.out.println("caught exception in main"); }
在Java中,如果要捕獲線程中的異常,需要通過UncaughtExceptionHandler實現。
UncaughtExceptionHandler是一個介面,只有一個方法:
void uncaughtException(Thread t, Throwable e)
當給定線程因給定的未捕獲異常而終止時,調用該方法。
所以,如果希望捕獲線程的異常,我們可以實現UncaughtExceptionHandler:
static class myUncaughtExceprionHandler implements UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { // TODO Auto-generated method stub System.out.println("caughtException in my handler"); System.out.println(e); } }
然後,線上程開始之前,設定線程的uncaughtExceptionHandler:
Thread thread = new Thread(new myRun()); thread.setUncaughtExceptionHandler(new myUncaughtExceprionHandler()); thread.start();
但是,在使用線程池的時候,問題來了,到底應該在哪設定uncaughtExceptionHandler。
這時候,需要自訂一個新的ThreadFactory:
static class HandlerThreadFactory implements ThreadFactory { @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setUncaughtExceptionHandler(new myUncaughtExceprionHandler()); return t; } }
然後通過如下方式運行程式:
ExecutorService exe = Executors.newCachedThreadPool(new HandlerThreadFactory()); exe.execute(new myRun());