小编典典

Java CompletableFuture的thenApply和thenApplyAsync有什么区别?

java

假设我有以下代码:

CompletableFuture<Integer> future  
        = CompletableFuture.supplyAsync( () -> 0);

thenApply 案件:

future.thenApply( x -> x + 1 )
      .thenApply( x -> x + 1 )
      .thenAccept( x -> System.out.println(x));

这里输出将2.现在的情况thenApplyAsync

future.thenApplyAsync( x -> x + 1 )   // first step
      .thenApplyAsync( x -> x + 1 )   // second step
      .thenAccept( x -> System.out.println(x)); // third step

我在这个博客中读到,每个步骤thenApplyAsync都是在单独的线程中执行的,并且“同时”执行(这意味着thenApplyAsyncs在先于thenApplyAsyncs结束之前先开始执行),如果是这样,那么如果第一步没有完成,那么第二步的输入参数值是多少?

如果第二步不采取措施,第一步的结果将流向何方?第三步将采取哪一步的结果?

如果第二步必须等待第一步的结果,那么意义何在Async

这里x-> x + 1只是为了说明这一点,我想知道的是在很长的计算情况下。


阅读 4021

收藏
2020-12-03

共1个答案

小编典典

区别Executor在于负责运行代码的。每个运算符CompletableFuture通常具有3个版本。

  1. thenApply(fn)- fnCompleteableFuture调用它的线程定义的线程上运行,因此您通常不知道在哪里执行该线程。如果结果已经可用,它可能会立即执行。
  2. thenApplyAsync(fn)- fn无论环境如何,都在环境定义的执行程序上运行。为此CompletableFuture通常ForkJoinPool.commonPool()
  3. thenApplyAsync(fn,exec)-运行fnexec

最后,结果是相同的,但是调度行为取决于方法的选择。

2020-12-03