CompletableFuture 实现异步总结(二)

前言

小白今天又来更新啦,上一节内容是 CompletableFuture 实现异步总结(一),今天跟大家分享的是 CompletableFuture 进阶部分。

一、CompletableFuture 提供了哪些方法?

对于 CompletableFuture 来说,我们会发现它本身提供了很多方法供开发使用,例如参考下面的小部分截图。

二、CompletableFuture 常用的回调方法

1.thenApply( )

thenApply( )方法:可以用于获取异步任务的结果。

        CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> {
            return "KARRY_wang_123";
        });

        CompletableFuture<String> stringCompletableFuture = supplyAsync.thenApply(str -> {
            String lowerCase = str.toLowerCase();
            return lowerCase;
        });

        //打印异步结果
        System.out.println(stringCompletableFuture.get());

2.thenAccept( )

thenAccept( )方法:在异步任务运行完成之后,需要结合上一步的结果,并处理一些次要代码。

        CompletableFuture.supplyAsync(() -> {
            String code = "karry_wang";
            return code;
        }).thenAccept((code) -> {
            System.out.println("code = " + code);
        });

3. thenRun( )

thenRun( ) 方法:可以适用于当异步任务完成后,不使用上一步异步任务的结果,且可以得知异步是否完成的通知。

        CompletableFuture.supplyAsync(() -> {
            String code = "karry_wang";
            return code;
        }).thenAccept((code) -> {
            System.out.println("code = " + code);
        }).thenRun(() -> {
            System.out.println("处理完成....");
        });

三、CompletableFuture 之异常处理

1. 异常处理方法对比如下:

方法名

不同点

exceptionally( )

且常用于异步任务的末端进行异常处理;

handle( )

用于针对某一个异步任务进行异常修复;

2. 代码示例:

(1)exceptionally( )方法:

        CompletableFuture.supplyAsync(() -> {
            String code = null;
            //代码运行到下面这行会报空指针异常,CompletableFuture 直接进入异常处理,          
            //即执行 exceptionally 方法
            int length = code.length();
            return length;
        }).thenAccept((code) -> {
            System.out.println("code = " + code);
        }).thenRun(() -> {
            System.out.println("处理完成....");
        }).exceptionally(ex -> {
            System.out.println("ex = " + ex);
            return null;
        });

(2)handle( )方法:

        CompletableFuture.supplyAsync(() -> {
            String code = null;
            int length = code.length();
            return length;
        }).handle((result, ex)-> {
            //上面的异步任务如果没有异常,则直接返回result,否则进入if相关的异常判断,打印异常
            if (ex != null){
                System.out.println("异常 = " + ex);
            }
            return result;
        });

补充:

这两个方法用于区别所使用的线程来源于哪个线程池,比如带有线程池入参的方法为自定义的线程池,且这两个方法对JDK的版本有要求,需要 JDK17+

CompletableFuture<R> exceptionallyAsync(Function<Throwable, R> fn)

CompletableFuture<R>exceptionallyAsync(Function<Throwable,R> fn,Executor executor)
 

今天的分享就到这啦,有什么问题还请各位大佬多多赐教哈,忙去喽~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值