標籤:調用 out dfa creat cto enc ring https new
在某些情境下,我們經常需要使用多線程來執行任務提高效能,但是我們知道正常的主線程是無法處理子線程的異常的,一旦出現異常就會傳播到控制台。這個時候我們需要線上程裡面處理異常怎麼辦呢,我們可以使用Executor來處理。
在Java5中新加入了一個Thread.UncaughtExceptionHandler介面,這個介面可以讓我們在每個Thread對象上都附著一個異常處理器,它的unacughtException()方法線程因未捕獲的異常而死亡時被調用。
首先我們我們先實現Thread.UncaughtExceptionHandler介面:
class myUncaughtExceptionhandler implements Thread.UncaughtExceptionHandler{//實現線程異常處理介面 @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("cause"+ e); }}
我們在自訂一個線程工廠:
class HandlerThreadFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { System.out.println(this+"create new thread"); Thread t = new Thread(r); System.out.println("create"+t); t.setUncaughtExceptionHandler(new myUncaughtExceptionhandler());//設定我們自訂的異常處理 //Thread.setDefaultUncaughtExceptionHandler();也可使用此方法設定預設的處理器 System.out.println("eh="+t.getUncaughtExceptionHandler()); return t; }}
最後我們實現一個Runnable介面,並在run方法中拋出一個異常:
class MyThread implements Runnable { @Override public void run() { Thread t = Thread.currentThread(); System.out.println("run()"+ t); System.out.println("eh="+t.getUncaughtExceptionHandler()); throw new RuntimeException(); }}
ok,我們再寫個main方法來測試一些:
public static void main(String[] args){ ExecutorService exe = Executors.newCachedThreadPool(new HandlerThreadFactory());//使用我們自訂的ThreadFactory exe.execute(new MyThread());}
運行結果如所示:
[email protected] new thread
createThread[Thread-0,5,main]
[email protected]
run()Thread[Thread-0,5,main]
[email protected]
[email protected] new thread
createThread[Thread-1,5,main]
[email protected]
causejava.lang.RuntimeException
很明顯,程式可以運行,說明異常被捕獲了,並且也是我們所拋出的異常,希望對大家有所協助。
消化於:72989497
Java多線程之捕獲子線程中的異常---面試經