相关文章推荐
瘦瘦的烤红薯  ·  SAML 要求 - Tableau·  1 年前    · 
大方的金针菇  ·  在 Windows 客户端设备上设置 ...·  1 年前    · 
力能扛鼎的饭卡  ·  写一个正则代码提取中文VBA - CSDN文库·  1 年前    · 
老实的雪糕  ·  表格存储常见错误_表格存储(Tablesto ...·  1 年前    · 
温文尔雅的火龙果  ·  python ...·  2 年前    · 
Code  ›  thenApply和thenApplyAsync of Java CompletableFuture有什么区别?开发者社区
https://cloud.tencent.com/developer/ask/sof/114720529/answer/137151294
刀枪不入的红薯
2 年前
首页
学习
活动
专区
工具
TVP 最新优惠活动
返回腾讯云官网
提问

问 thenApply和thenApplyAsync of Java CompletableFuture有什么区别?

Stack Overflow用户
提问于 2017-11-25 18:37:44
EN

假设我有以下代码:

CompletableFuture<Integer> future  
        = CompletableFuture.supplyAsync( () -> 0);

thenApply 案件:

future.thenApply( x -> x + 1 )
      .thenApply( x -> x + 1 )
      .thenAccept( x -> System.out.println(x));

这里的输出是2,如果是 thenApplyAsync 的话

future.thenApplyAsync( x -> x + 1 )   // first step
      .thenApplyAsync( x -> x + 1 )   // second step
      .thenAccept( x -> System.out.println(x)); // third step

我在这个 博客 中看到,每个 thenApplyAsync 都是在一个单独的线程中执行的,并且“同时执行”(这意味着在 thenApplyAsyncs 完成之前执行 thenApplyAsyncs ),如果是这样的话,如果第一步没有完成,那么第二步的输入参数值是多少?

如果第二步不采取,第一步的结果将如何?第三步将采取哪一步的结果?

如果第二步必须等待第一步的结果,那么 Async 的意义是什么?

这里,x -> x+1只是为了说明这一点,我想知道的是在非常长的计算情况下。

4 30.3K 0 票数 79
EN
java
completable-future

Stack Overflow用户

发布于 2022-09-06 08:01:03

在 thenApplyAsync 和 thenApply 中,传递给这些方法的 Consumer<? super T> action 将被异步调用,不会阻塞指定使用者的线程。

这种差异与哪个线程负责调用方法 Consumer#accept(T t) 有关。

AsyncHttpClient 考虑如下所示的调用: 注意下面打印的线程名。我希望它能让你弄清楚其中的区别:

// running in the main method
// public static void main(String[] args) ....
CompletableFuture<Response> future =
    asyncHttpClient.prepareGet(uri).execute().toCompletableFuture();
log.info("Current Thread " + Thread.currentThread().getName());
//Prints "Current Thread main"

thenApply 将使用与完成未来相同的线程。

//will use the dispatcher threads from the asyncHttpClient to call `consumer.apply`
//The thread that completed the future will be blocked by the execution of the method `Consumer#accept(T t)`.
future.thenApply(myResult -> {
    log.info("Applier Thread " + Thread.currentThread().getName());
    return myResult;
//Prints: "Applier Thread httpclient-dispatch-8"

thenApplyAsync 将使用执行器池中的线程.

//will use the threads from the CommonPool to call `consumer.accept`
//The thread that completed the future WON'T be blocked by the execution of the method `Consumer#accept(T t)`.
future.thenApplyAsync(myResult -> {
 
推荐文章
瘦瘦的烤红薯  ·  SAML 要求 - Tableau
1 年前
大方的金针菇  ·  在 Windows 客户端设备上设置 Azure Monitor 代理 - Azure Monitor | Microsoft Learn
1 年前
力能扛鼎的饭卡  ·  写一个正则代码提取中文VBA - CSDN文库
1 年前
老实的雪糕  ·  表格存储常见错误_表格存储(Tablestore)-阿里云帮助中心
1 年前
温文尔雅的火龙果  ·  python numpy库--学习_创建一个长度为10的空向量-CSDN博客
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号