CompletableFuture处理异步结算的结果 thenApply()

小王曾是少年 怪见溪童出门望,雀声先我到山家
阿里巴巴Java开发工程师
博客专家认证
2022-01-14 23:09:24

当我们获取到异步计算的结果之后,还可以对其进行进一步的处理,比较常用的方法有下面几个:

  • thenApply()
  • thenAccept()
  • thenRun()
  • whenComplete()

thenApply() 方法接受一个 Function 实例,用它来处理结果。

// 沿用上一个任务的线程池
public <U> CompletableFuture<U> thenApply(
    Function<? super T,? extends U> fn) {
    return uniApplyStage(null, fn);
}

//使用默认的 ForkJoinPool 线程池(不推荐)
public <U> CompletableFuture<U> thenApplyAsync(
    Function<? super T,? extends U> fn) {
    return uniApplyStage(defaultExecutor(), fn);
}
// 使用自定义线程池(推荐)
public <U> CompletableFuture<U> thenApplyAsync(
    Function<? super T,? extends U> fn, Executor executor) {
    return uniApplyStage(screenExecutor(executor), fn);
}

thenApply() 方法使用示例如下:

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
        .thenApply(s -> s + "world!");
assertEquals("hello!world!", future.get());
// 这次调用将被忽略。
future.thenApply(s -> s + "nice!");
assertEquals("hello!world!", future.get());

你还可以进行 流式调用

CompletableFuture<String> future = CompletableFuture.completedFuture("hello!")
        .thenApply(s -> s + "world!").thenApply(s -> s + "nice!");
assertEquals("hello!world!nice!", future.get());

如果你不需要从回调函数中获取返回结果,可以使用 thenAccept() 或者 thenRun()。这两个方法的区别在于 thenRun() 不能访问异步计算的结果。

 

...全文
280 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
CSDN-Ada助手 2023-01-13
  • 打赏
  • 举报
回复
您可以前往 CSDN问答-Java 发布问题, 以便更快地解决您的疑问

508,674

社区成员

发帖
与我相关
我的任务
社区描述
我命由我不由天,来吧,和哪吒一起奋发图强,搬砖工逆袭Java架构师!
社区管理员
  • 哪 吒
  • Baker-Chen
  • 是Lay
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

【Java技能树】和哪吒一起,打卡100天,每天分享一个知识点,一起学习,一起进步,告别CRUD,搬砖工逆袭Java架构师,加油!

【积分榜】积分榜前十每周都有精彩礼包赠送!

【添加微信】备注1024,加入哪吒微信交流群,一起学习交流进大厂

试试用AI创作助手写篇文章吧