【java併發編程】多線程異常處理

1.場景

​ 多線程充分發揮了系統的性能,但是調用Thread.start()方法之後,如果線程有異常造成線程終止,主線程無法及時獲取。

  public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            //todo 添加要執行內容
            for(int i=0;i<10;i++){
                if(i==2){
                    // 模擬出現異常
                    throw new NullPointerException();
                }
            }
            // todo 添加要執行的內容
            System.out.println("執行完成");
        });
        thread.start();
        System.out.println("主線程執行完成");
    }

主線程執行完成
Thread-0拋出異常
Exception in thread “Thread-0” java.lang.NullPointerException
at com.example.demo.ChannelTest.lambda$main$0(ChannelTest.java:18)
at java.lang.Thread.run(Thread.java:748)

​ 如上代碼,主線程無法對子線程進行異常的捕獲處理。

2.UncaughtExceptionHandler接口

​ JDK1.5之後,爲了解決線程run()方法的異常無法捕獲的問題,引入了UncaughtExceptionHandler接口,該接口是Thread的內部類定義的。

//當線程拋出異常之後,會調用此方法
void uncaughtException(Thread t, Throwable e);

通過實現UncaughtExceptionHandler接口可以對拋出異常的線程做處理(記錄日誌),

public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"拋出異常");
           throw new NullPointerException();
        });
        thread.setUncaughtExceptionHandler(new GetException());
        thread.start();
    }
    static  class GetException implements Thread.UncaughtExceptionHandler {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("異常被捕獲");
            System.out.println(t.getName());
            System.out.println(e);
        }
    }
}

輸出:

Thread-0拋出異常
異常被捕獲
Thread-0
java.lang.NullPointerException

這樣,就可以在多線程使用的時候進行異常處理。通過異常處理就可以使程序更加健壯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章