(異常處理也是在子線程中執行,至關於在子線程中加上了一個異常攔截器,可使用下面的程序驗證)java
(1)Thread.setUncaughtExceptionHandler設置當前線程的異常處理器ide
(2)Thread.setDefaultUncaughtExceptionHandler爲整個程序設置默認的異常處理器函數
(3)new Thread(new ThreadTest() ,new runable{})時傳入 ThreadGroup spa
import java.util.concurrent.*; public class ThreadTest extends ThreadGroup{ private ThreadTest(){ super("ThreadTest"); } public static void main(String[] args) { System.out.println(Thread.currentThread().getId()); Thread t1=new Thread(new ThreadTest(),new Runnable() {//傳入繼承ThreadGroup的類對象 @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } if (1==1){ throw new NullPointerException("111"); } } }); t1.start(); /*ExecutorService executorService = Executors.newFixedThreadPool(8); Future future = executorService.submit(()->{ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } if (1==1){ throw new NullPointerException("111"); } return 1; }); try { future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { //e.getCause().printStackTrace(); e.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } executorService.shutdownNow();*/ } public void uncaughtException(Thread thread, Throwable exception) { /** * 當線程拋出unckecked異常時,系統會自動調用該函數,可是是在拋出異常的線程內執行*/ System.out.println(Thread.currentThread().getId()); System.out.println(thread.getId()); exception.printStackTrace();//example, print stack trace } }