使用CompletableFuture在主线程捕获子线程异常

场景:我们使用线程池的时候,假如说某个线程出现了异常此时我们需要将异常捕获打印出相应的异常日志

这个时候就可以用到CompletableFuture的exceptionally方法,其作用是返回一个新的CompletableFuture,如果原CompletableFuture以异常的方式完成,则使用提供的方法来计算新CompletableFuture的值。

下面给出代码演示一下

    public static final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 100, 20, TimeUnit.SECONDS, new LinkedBlockingDeque<>(10), new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        //执行任务
        for (int i = 20; i >= 0; i--) {
            int finalI = i;
            CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> mission(finalI), executor)
                    .exceptionally(e -> {
                        System.out.println("子线程出现异常 异常信息:" + e.getMessage());
                        return -1;
                    });
            futures.add(completableFuture);
        }

        //将收集到的结果放入到list中用于遍历
        List<Integer> list = new ArrayList<>();

        for (CompletableFuture<Integer> future : futures) {
            try {
                list.add(future.get()); // 等待 CompletableFuture 完成并获取结果
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println(list);
    }

    public static int mission(int i) {
        return 10 % i;
    }

最后的执行结果如下

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值