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() {

        @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

你可能感兴趣的:(ThreadPoolExecutor捕获线程执行失败抛出的异常)