首页 > 解决方案 > 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

标签: javamultithreading

解决方案


您错误地认为 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(). 但除此之外,无法保证它运行在池中的哪个线程上。


推荐阅读