Java Thread.UncaughtExceptionHandler__Java

來源:互聯網
上載者:User

如果在java中定義了如下的類,希望在多線程環境下,捕獲異常

    static class myRun implements Runnable {        @Override        public void run() {            System.out.println("myRun.run()");            throw new RuntimeException();        }    }

那麼通過如下兩種方式,是不能在調用這兩個線程的程式中,捕獲到異常的。

         try {         new Thread(new myRun()).start();         } catch (Exception e) {         // TODO: handle exception         System.out.println("caught exception in main");         }        try {            Executors.newCachedThreadPool().execute(new myRun());        } catch (Exception e) {            // TODO: handle exception            System.out.println("caught exception in main");        }

在Java中,如果要捕獲線程中的異常,需要通過UncaughtExceptionHandler實現。

UncaughtExceptionHandler是一個介面,只有一個方法:

void uncaughtException(Thread t, Throwable e)
當給定線程因給定的未捕獲異常而終止時,調用該方法。

所以,如果希望捕獲線程的異常,我們可以實現UncaughtExceptionHandler:

    static class myUncaughtExceprionHandler implements UncaughtExceptionHandler {        @Override        public void uncaughtException(Thread t, Throwable e) {            // TODO Auto-generated method stub            System.out.println("caughtException in my handler");            System.out.println(e);        }    }

然後,線上程開始之前,設定線程的uncaughtExceptionHandler:

         Thread thread = new Thread(new myRun());         thread.setUncaughtExceptionHandler(new myUncaughtExceprionHandler());         thread.start();

但是,在使用線程池的時候,問題來了,到底應該在哪設定uncaughtExceptionHandler。

這時候,需要自訂一個新的ThreadFactory:

    static class HandlerThreadFactory implements ThreadFactory {        @Override        public Thread newThread(Runnable r) {            Thread t = new Thread(r);            t.setUncaughtExceptionHandler(new myUncaughtExceprionHandler());            return t;        }    }

然後通過如下方式運行程式:

         ExecutorService exe = Executors.newCachedThreadPool(new         HandlerThreadFactory());         exe.execute(new myRun());

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.