ThreadPoolExecutor捕獲線(xiàn)程執(zhí)行失敗拋出的異常

當(dāng)我們通過(guò)submit提交任務(wù)到線(xiàn)程池,如果線(xiàn)程失敗,我們?cè)趺慈ゲ东@這個(gè)失敗而拋出來(lái)的異常呢

方法1:通過(guò)調(diào)用返回對(duì)象 FutureTask的get方法**

  • FutureTask.get() will re-throw any exception thrown by the task as an ExecutorException

  • 缺點(diǎn):該方法是阻塞調(diào)用,會(huì)阻塞提交任務(wù)的線(xiàn)程

方法2:在提交的線(xiàn)程任務(wù)的 run() or call()使用 try{}catch{}Exceptoion{}進(jìn)行處理

Executors.newCachedThreadPool().submit(new Callable<Integer>() {

        @Override

        public Integer call() throws Exception {

                try {

                        int a = 1 / 0;

                        return 1;

                    } catch (Exception e) {

                            e.printStackTrace();

                    } finally {

                       //you can do something here,e.g.  log execution

                    }

                return 0;

         }

});

方法3:改寫(xiě)ThreadPoolExecutor的afterExecute方法

方法示例來(lái)自jdk的ThreadPoolExecutor的afterExecute方法注釋

class ExtendedExecutor extends ThreadPoolExecutor {

   // ...

   protected void afterExecute(Runnable r, Throwable t) {

       super.afterExecute(r, t);

       if (t == null && r instanceof Future<?>) {

            try {

                   Object result = ((Future<?>) r).get();

            } catch (CancellationException ce) {

                  t = ce;

            } catch (ExecutionException ee) {

                  t = ee.getCause();

             catch (InterruptedException ie) {

                 Thread.currentThread().interrupt(); // ignore/reset

            }

       }

      if (t != null)

            System.out.println(t);

      }

}

參考資料:https://stackoverflow.com/questions/2554549/handling-exceptions-for-threadpoolexecutor

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容