標籤:
由於線程的特性,當我們啟動了線程是沒有辦法用try catch捕獲異常的,如下例:
1 package com.xt.thinks21_2; 2 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 6 /** 7 * 線程異常捕獲測試 8 * 9 * @author xue10 *11 */12 public class ThreadUncaughtExceptionTest implements Runnable {13 14 @Override15 public void run() {16 // TODO Auto-generated method stub17 throw new NullPointerException();18 }19 20 public static void main(String[] args) {21 try {22 ExecutorService es = Executors.newCachedThreadPool();23 es.execute(new ThreadUncaughtExceptionTest());24 es.shutdown();25 // or this26 // Thread t = new Thread(new ThreadUncaughtExceptionTest());27 // t.start();28 } catch (Exception e) {29 // TODO: handle exception30 }31 32 }33 }
列印異常資訊為:
Exception in thread "pool-1-thread-1" java.lang.NullPointerException
at com.xt.thinks21_2.ThreadUncaughtExceptionTest.run(ThreadUncaughtExceptionTest.java:17)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
此時,我們需要為線程定製工廠類來生產線程,為線程指定UncaughtExceptionHandler
1 package com.xt.thinks21_2; 2 3 import java.lang.Thread.UncaughtExceptionHandler; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.Executors; 6 import java.util.concurrent.ThreadFactory; 7 8 /** 9 * 未捕獲異常執行程式10 * 11 * @author Administrator12 *13 */14 class ThreadUncaughtExceptionHandler implements UncaughtExceptionHandler {15 16 @Override17 public void uncaughtException(Thread t, Throwable e) {18 // TODO Auto-generated method stub19 System.out.println("caught:" + e);20 }21 22 }23 24 /**25 * 線程工廠26 * 27 * @author Administrator28 *29 */30 class HandlerThreadExceptionFactory implements ThreadFactory {31 32 @Override33 public Thread newThread(Runnable r) {34 // TODO Auto-generated method stub35 Thread t = new Thread(r);36 t.setUncaughtExceptionHandler(new ThreadUncaughtExceptionHandler());37 return t;38 }39 40 }41 42 /**43 * 線程異常捕獲測試44 * 45 * @author xue46 *47 */48 public class ThreadUncaughtExceptionTest implements Runnable {49 50 @Override51 public void run() {52 // TODO Auto-generated method stub53 throw new NullPointerException();54 }55 56 public static void main(String[] args) {57 ExecutorService es = Executors58 .newCachedThreadPool(new HandlerThreadExceptionFactory());59 es.execute(new ThreadUncaughtExceptionTest());60 es.shutdown();61 }62 }
此時,我們就可以看到異常資訊被捕獲到了:
caught:java.lang.NullPointerException
JAVA並發,線程異常捕獲