设为首页 加入收藏

TOP

12分钟从Executor自顶向下彻底搞懂线程池(六)
2023-09-09 10:25:36 】 浏览:118
Tags:12分 钟从 Executor 向下彻 程池
rue;         } catch (Throwable ex) {              //出现异常 封装到FutureTask              result = null;              ran = false;              setException(ex);         }          //..     }

等到执行get时,先阻塞、直到完成任务再来判断状态,如果状态不正常则抛出封装的异常

     private V report(int s) throws ExecutionException {
         Object x = outcome;
         if (s == NORMAL)
             return (V)x;
         if (s >= CANCELLED)
             throw new CancellationException();
         throw new ExecutionException((Throwable)x);
     }

因此在处理Callable任务时,可以对任务进行捕获也可以对get进行捕获

         //捕获任务
         Future<?> f = threadPool.submit(() -> {
             try {
                 int i = 1;
                 int j = 0;
                 return i / j;
             } catch (Exception e) {
                 System.out.println(e);
             } finally {
                 return null;
             }
         });
 ?
         //捕获get
         Future<Integer> future = threadPool.submit(() -> {
             int i = 1;
             int j = 0;
             return i / j;
         });
 ?
         try {
             Integer integer = future.get();
         } catch (Exception e) {
             System.out.println(e);
         }
afterExecutor

还记得线程池的runWorker吗?

它在循环中不停的获取阻塞队列中的任务执行,在执行前后预留钩子方法

继承ThreadPoolExecutor来重写执行后的钩子方法,记录执行完是否发生异常,如果有异常则进行日志记录,作一层兜底方案

 public class MyThreadPool extends ThreadPoolExecutor {  
     //...
     
     @Override
     protected void afterExecute(Runnable r, Throwable t) {
         //Throwable为空 可能是submit提交 如果runnable为future 则捕获get
         if (Objects.isNull(t) && r instanceof Future<?>) {
             try {
                 Object res = ((Future<?>) r).get();
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
             } catch (ExecutionException e) {
                 t = e;
             }
         }
 ?
         if (Objects.nonNul
首页 上一页 3 4 5 6 7 8 9 下一页 尾页 6/9/9
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇适配器模式:如何让不兼容的接口.. 下一篇原型模式和深拷贝,浅拷贝

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目