三、CompletableFuture(二)常见用法
注:
方法名以”Async“结尾的区别:(如thenApply和thenApplyAsync)
thenApply:当前任务的线程继续执行“thenApply”的任务。
thenApplyAsync:把“thenApplyAsync”这个任务继续交给线程池来进行执行。
一、获得结果和触发计算
1、获取结果
get():同Future的get()。
get(long timeout, TimeUnit unit):同Future的get()。
join():同get()。join不报异常,get会报异常。
getNow(T valueIfAbsent):立即获取计算值,如果未计算完,则返回设定的默认值valueIfAbsent。
2、主动触发计算
complete(T value):立即打断异步执行。如果打断成功返回true,此时get会得到设定的默认值value。打断失败返回false,此时get会得到异步执行的结果。
二、对计算结果进行处理
...thenApply(i -> { return i + 2; }).handle((i, e) -> { return i + 3; })...
i:上一步的计算结果
e:异常
1、thenApply
计算结果存在依赖关系,step by step。
由于存在依赖关系,当前步骤异常时,不会继续下一步。
2、handle
有异常也可以继续下一步,根据带的异常参数可以进一步处理。
三、对计算结果进行消费
thenAccept:接收任务的返回结果,并消费处理,无返回结果。
四、对计算速度进行选用
applyToEither:返回最快执行完的结果。最快返回后,其他线程依然会继续执行。

public static void main(String[] args) { try { CompletableFuture future = CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停6秒钟"); TimeUnit.SECONDS.sleep(6); System.out.println(Thread.currentThread().getName() + "完成6秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 6; }).applyToEither(CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停5秒钟"); TimeUnit.SECONDS.sleep(5); System.out.println(Thread.currentThread().getName() + "完成5秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 5; }), r -> r).applyToEither(CompletableFuture.supplyAsync(() -> { try { System.out.println(Thread.currentThread().getName() + "暂停4秒钟"); TimeUnit.SECONDS.sleep(4); System.out.println(Thread.currentThread().getName() + "完成4秒钟"); } catch (InterruptedException e) { e.printStackTrace(); } return 4; }), r -> r); System.out.println(future.join()); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Exception e) { } }
五、对计算结果进行合并
thenCombine:合并多个任务的执行结果。(如调用多个接口合并处理后返回前端)

public static void main(String[] args) { try { CompletableFuture future = CompletableFuture.supplyAsync(() -> { return 10; }).thenCombine(CompletableFuture.supplyAsync(() -> { return 20; }), (r1, r2) -> { return r1 + r2; }); System.out.println(future.join()); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Exception e) { } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)