Java線程學習筆記(兩) 線程異常處理

來源:互聯網
上載者:User

標籤:

線程捕獲異常:

情況下,我們在main()方法裡是捕捉不到線程的異常的,比例如以下面代碼:

public class ExceptionThread implements Runnable{    @Override    public void run() {        throw new NullPointerException();    }    public static void main(String[] args) {        ExecutorService executorService = Executors.newCachedThreadPool();        try {            System.out.println("運行線程");            executorService.execute(new ExceptionThread());        } catch (Exception e) {            e.printStackTrace();            System.out.println("捕捉異常");        }    }}
上述代碼並不能在main方法裡捕捉線程異常,那麼我們怎麼才幹捕捉到線程的異常資訊呢?

以下我們看這段代碼

/** * 定義異常線程內容 */class MyExceptionThread implements Thread.UncaughtExceptionHandler {    @Override    public void uncaughtException(Thread t, Throwable e) {        // 捕捉異常後的業務處理放在這裡        System.out.println("捕捉的異常資訊例如以下");        System.out.println(e);    }}/** * 定義異常線程工廠 */class ExceptionThreadFactory implements ThreadFactory {    @Override    public Thread newThread(Runnable r) {        Thread thread = new Thread(r);        // 此處是捕捉異常的設定。        thread.setUncaughtExceptionHandler(new MyExceptionThread());        return thread;    }}/** * 執行線程 */class ExceptionThread2 implements Runnable{    @Override    public void run() {        try {            Thread.sleep(1000l);        } catch (InterruptedException e) {            e.printStackTrace();        }        // 拋出異常        throw new NullPointerException();    }    public static void main(String[] args) {        // 通過我們自己寫的ExceptionThreadFactory線程工廠,構造線程池        ExecutorService executorService = Executors.newCachedThreadPool(new ExceptionThreadFactory());        try {            System.out.println("執行線程");            // 啟動三個線程            executorService.execute(new ExceptionThread2());            executorService.execute(new ExceptionThread2());            executorService.execute(new ExceptionThread2());        } catch (Exception e) {            e.printStackTrace();            System.out.println("捕捉異常");        }    }}
上面的輸出結果是
運行線程捕捉的異常資訊例如以下java.lang.NullPointerException捕捉的異常資訊例如以下java.lang.NullPointerException捕捉的異常資訊例如以下java.lang.NullPointerException
得出的結論是:main()該方法仍然沒有捕捉到異常的線程,當然,這個設定是合理的。現在每個線程都有自己的異常處理機制,怎麼辦呢,句子,建立一個線程時,該語句是好的~

收工。

Java線程學習筆記(兩) 線程異常處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.