Java多線程之捕獲子線程中的異常---面試經

來源:互聯網
上載者:User

標籤:調用   out   dfa   creat   cto   enc   ring   https   new   

在某些情境下,我們經常需要使用多線程來執行任務提高效能,但是我們知道正常的主線程是無法處理子線程的異常的,一旦出現異常就會傳播到控制台。這個時候我們需要線上程裡面處理異常怎麼辦呢,我們可以使用Executor來處理。

在Java5中新加入了一個Thread.UncaughtExceptionHandler介面,這個介面可以讓我們在每個Thread對象上都附著一個異常處理器,它的unacughtException()方法線程因未捕獲的異常而死亡時被調用。

首先我們我們先實現Thread.UncaughtExceptionHandler介面:

 

class myUncaughtExceptionhandler implements Thread.UncaughtExceptionHandler{//實現線程異常處理介面    @Override    public void uncaughtException(Thread t, Throwable e) {        System.out.println("cause"+ e);    }}

我們在自訂一個線程工廠:

class HandlerThreadFactory implements ThreadFactory{    @Override    public Thread newThread(Runnable r) {        System.out.println(this+"create new thread");        Thread t = new Thread(r);        System.out.println("create"+t);        t.setUncaughtExceptionHandler(new myUncaughtExceptionhandler());//設定我們自訂的異常處理        //Thread.setDefaultUncaughtExceptionHandler();也可使用此方法設定預設的處理器        System.out.println("eh="+t.getUncaughtExceptionHandler());        return t;    }}

最後我們實現一個Runnable介面,並在run方法中拋出一個異常:

class MyThread implements Runnable {    @Override    public void run() {        Thread t = Thread.currentThread();        System.out.println("run()"+ t);        System.out.println("eh="+t.getUncaughtExceptionHandler());        throw new RuntimeException();    }}

ok,我們再寫個main方法來測試一些:

public static void main(String[] args){    ExecutorService exe = Executors.newCachedThreadPool(new HandlerThreadFactory());//使用我們自訂的ThreadFactory    exe.execute(new MyThread());}

運行結果如所示:

 

[email protected] new thread
createThread[Thread-0,5,main]
[email protected]
run()Thread[Thread-0,5,main]
[email protected]
[email protected] new thread
createThread[Thread-1,5,main]
[email protected]
causejava.lang.RuntimeException

很明顯,程式可以運行,說明異常被捕獲了,並且也是我們所拋出的異常,希望對大家有所協助。

 

消化於:72989497

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.