具有CompletableFuture的TheApplyAsync使用与SupplyAsync线程相同的线程

时间:2019-10-16 23:45:15

标签: java multithreading

我是Java线程的新手,我正在尝试学习completableFuture API的工作方式。当我运行下面的代码时,我得到线程名称输出,如下所示。 SupplyAsync和ThenApplyAsync似乎正在使用同一线程,即ForkJoinPool.commonPool-worker-1。我的理解是,如果我使用ThenApplyAsync,那么ThenApplyAsync将使用与SupplyAsync不同的线程。你能告诉我这是怎么回事吗?谢谢!

代码

      override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
            self.bottomConstraint.isActive = false
            self.topConstraint.isActive = true
    self.view.layoutIfNeeded()
}

输出:

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());
    }

1 个答案:

答案 0 :(得分:1)

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