Java執行緒未捕獲異常處理
阿新 • • 發佈:2019-02-06
public void mainGroup() throws InterruptedException { Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("I catch a exception from " + Thread.currentThread().getName() + ":" + Thread.currentThread().getThreadGroup().getName()); } }); new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " said my thread group is " + Thread.currentThread().getThreadGroup().getName()); new Thread(new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName() + " said my thread group is " + Thread.currentThread().getThreadGroup().getName()); int i = 1/0; } }, "thread2").start(); } }, "thread1").start(); Thread.sleep(10); }
這個方法中,首先建立啟動了一個執行緒,然後又在這個執行緒中建立啟動了另一個執行緒,它們都沒有主動設定執行緒組。然而,它們都是有執行緒組的,其執行的結果如下: