gpt4 book ai didi

java - TheApplyAsync 与 CompletableFuture 使用与 SupplyAsync 线程相同的线程

转载 作者:行者123 更新时间:2023-12-02 09:24:37 25 4
gpt4 key购买 nike

我是 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.

它使用与前一阶段相同的执行设施,即 ForkJoinPool.commonPool() 。但除此之外,无法保证它在池中的哪个线程上运行。

关于java - TheApplyAsync 与 CompletableFuture 使用与 SupplyAsync 线程相同的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com