CompletableFuture thenApply 在单独的线程中运行,而不是在调用者线程中运行?

问题描述 投票:0回答:1

当我执行

thenApply
CompletableFuture
方法时,此方法的执行发生在
ForkJoinPool
线程中,而不是调用者(主)线程中。 为什么会这样? 这个结果,即使用 fork 连接池而不是调用线程类似于调用
thenApplyAsync
,所以我想了解
thenApply

的这种行为背后的原因
        System.out.println("hello world, CompletableFuturesRightHere");
        System.out.println("log1: " + Thread.currentThread().getName());

        CompletableFuture<Integer> cf = CompletableFuture.supplyAsync(() -> {
            System.out.println("log-sA: " + Thread.currentThread().getName());
            return 40;
        }).thenApply( a ->  {
            System.out.println("log-tA: " + Thread.currentThread().getName());
            return a + 40;
        });

        System.out.println("log3: " + Thread.currentThread().getName());
        System.out.println("cf result: " + cf.get());

以上输出:

hello world, CompletableFuturesRightHere
log1: main
log-sA: ForkJoinPool.commonPool-worker-3
log3: main
log-tA: ForkJoinPool.commonPool-worker-3
cf result: 80

当我在 jdoodle 中运行相同的代码时,行为符合预期。

java multithreading java.util.concurrent completable-future
1个回答
1
投票

CompletableFuture
文档状态

为非异步方法的依赖完成提供的操作可以由完成当前 CompletableFuture 的线程执行,或由完成方法的任何其他调用者执行。

这涵盖了您描述的两种行为;要么,fork 连接池中的原始线程被重用(输出中的“ForkJoinPool.commonPool-worker-3”)用于下一个完成阶段,或者调用线程在前一个阶段完成后被使用。

使用

thenApplyAsync
将能够使用与公共池不同的线程。

© www.soinside.com 2019 - 2024. All rights reserved.