java - TheApplyAsync with CompletableFuture 使用与 SupplyAsync 线程相同的线程
问题描述
我是 Java 线程的新手,我正在尝试了解 completableFuture API 的工作原理。当我运行下面的代码时,我得到了线程名称输出,如下所示。SupplyAsync 和 ThenApplyAsync 似乎使用同一个线程,即 ForkJoinPool.commonPool-worker-1。我的理解是,如果我使用 ThenApplyAsync,那么 ThenApplyAsync 使用与 SupplyAsync 不同的线程。你能告诉我这里发生了什么吗?谢谢!
代码:
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println("Current Thread : " + Thread.currentThread().getName());
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("Current Thread (SupplyAsync) : " + Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ex) {
throw new IllegalStateException(ex);
}
return "Result";
}).thenApplyAsync(result -> {
System.out.println("Current Thread (ThenApplyAsync) : " + Thread.currentThread().getName());
return result.toUpperCase();
});
System.out.println("CompletableFuture Result : " + future.get());
}
输出:
Current Thread : main
Current Thread (SupplyAsync) : ForkJoinPool.commonPool-worker-1
Current Thread (ThenApplyAsync) : ForkJoinPool.commonPool-worker-1
CompletableFuture Result : RESULT
解决方案
您错误地认为 thenApplyAsync 将使用与前一个完成阶段不同的线程。
<U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)
Returns a new CompletionStage that, when this stage completes normally, is executed using this stage's default asynchronous execution facility, with this stage's result as the argument to the supplied function.
它使用与前一阶段相同的 executionFacility,即ForkJoinPool.commonPool()
. 但除此之外,无法保证它运行在池中的哪个线程上。
推荐阅读
- wordpress - 没有尾随/的链接的WordPress站点重定向问题
- java - 如果我无法使用注释标记该类,如何在反序列化期间为类自定义 json 包装键?
- sql - 带有日期列的完全外部自联接
- c - 避免 POSIX 线程中的内存泄漏
- java - 如何通过 config.properties 从 pom.xml 获取参数值
- javascript - problem with conditions in javascript while working with DOM
- c - Why I have error: deprecated conversion from string constant to 'char*' [-Wwrite-strings] in the line 5 and 6?
- facebook - Drupal 8 - 简单的 fb 连接失败
- excel - (Excel)如何在一个单元格中测试多个值?
- azure - 如何将 Azure Policy 与 Azure DevOps 集成?