【问题标题】:CompletableFuture is blocking threadCompletableFuture 正在阻塞线程
【发布时间】:2021-09-13 09:16:00
【问题描述】:
 CompletableFuture<HttpResponse<String>> completableFuture =
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    completableFuture
        .thenApplyAsync(HttpResponse::headers)
        .thenAcceptAsync(System.out::println);
    HttpResponse<String> response = completableFuture.join();

sysout("test");

join() 调用后没有打印输出,join 等待完成请求。 为什么?

【问题讨论】:

  • 嗯...编辑后的问题与原始问题无关。
  • 不要编辑您的帖子以完全改变您的要求,从而使现有答案无效。如果您有新问题,请创建一个新帖子。

标签: java concurrency


【解决方案1】:

因为这是 join 应该做的 - 等待完成。

【讨论】:

  • 那么我怎样才能在不阻塞的情况下得到结果呢?
  • 不要使用join,你会在未来的某个时刻得到结果,消费者回调将应用于结果(你传递给thenApplyAsync的方法)
  • 我该怎么办?
  • 没什么,使用回调以异步方式消费结果。
【解决方案2】:

join 是一个阻塞调用 ans 等待直到 completableFuture 完成。 IOW,通过调用join,您可以将异步代码转换为同步代码。

【讨论】:

  • 那我怎样才能在不阻塞的情况下得到结果呢?我希望 sysout 打印然后结果来了。在
  • .thenRun(() -&gt; sysout("test));
  • 我想,代码块不会在异步调用中继续执行,因为很多人想运行
  • 不要与thenRunthenRunAsync 混淆。从调用者的角度来看,CompletableFuture 的大多数方法都是异步运行的。当CompletableFuture#complete 被调用时,thenXxxAsync 在与complete 不同的线程中被调用。这就是为什么所有xxxAsync 方法都有一个版本来明确指定要使用的线程池。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
  • 2016-01-27
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多