您当前的位置: 首页 > 

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

CompletableFuture异步编排(handle最终处理)

小志的博客 发布时间:2022-08-23 22:20:00 ,浏览量:0

目录
    • 一、CompletableFuture源码中handle最终处理方法
    • 二、handleAsync方法代码示例

一、CompletableFuture源码中handle最终处理方法
  • handle和whenComplete方法类似,但是whenComplete能感知异常但是不能返回结果。只能通过exceptionally进行处理。

  • handle即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。

    在这里插入图片描述

二、handleAsync方法代码示例
  • handleAsync方法:即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。
  • 代码示例
    package com.xz.thread.day1;
    import lombok.SneakyThrows;
    
    import java.util.concurrent.*;
    /**
     * @description: whenComplete方法:能感知异常但是不能返回结果。只能通过exceptionally进行处理。
     *              handle方法:即可以获取执行结果,也可以感知异常信息,并能处理执行结果并返回。
     * @author: xz
     * @create: 2022-08-23
     */
    public class Test7 {
        /**
         * 定义线程池
         */
        public static ExecutorService service = Executors.newFixedThreadPool(3);
    
        @SneakyThrows
        public static void main(String[] args) {
            System.out.println("main start ...");
    
            CompletableFuture future = CompletableFuture.supplyAsync(() -> {
                System.out.println("开启异步任务...");
                int i = 10 % 2;
                if (i == 0) {
                    throw new RuntimeException("远程服务调用失败");
                }
                return i;
            }, service).handleAsync((res, thr) -> {
                System.out.println("进入handleAsync方法");
                if (res != null) {
                    return res * 2;
                }
                if (thr != null) {
                    System.out.println("捕获到异常:" + thr);
                    return 0;
                }
                return 10;
            }, service);
    
            System.out.println("获取异步任务返回值:" + future.get());
            System.out.println("main end ...");
        }
    }
    
  • 输出结果 在这里插入图片描述
  • 如果去掉异常信息,可以看到如下返回值,最终异步执行结果为0 在这里插入图片描述
关注
打赏
1661269038
查看更多评论
立即登录/注册

微信扫码登录

0.0434s