ThreadPoolExecutor捕获线程执行失败抛出的异常

当我们通过submit提交任务到线程池,如果线程失败,我们怎么去捕获这个失败而抛出来的异常呢

方法1:通过调用返回对象 FutureTask的get方法**

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

  • 缺点:该方法是阻塞调用,会阻塞提交任务的线程

方法2:在提交的线程任务的 run() or call()使用 try{}catch{}Exceptoion{}进行处理

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:改写ThreadPoolExecutor的afterExecute方法

方法示例来自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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容