假设我有以下代码:
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 只是为了说明这一点,我想知道的是在计算时间很长的情况下。
原文由 Yulin 发布,翻译遵循 CC BY-SA 4.0 许可协议
不同之处在于
Executor
负责运行代码。CompletableFuture
上的每个运营商一般有3个版本。thenApply(fn)
- 在调用它的CompleteableFuture
定义的线程上运行fn
,所以你通常不知道它会在哪里执行。如果结果已经可用,它可能会立即执行。thenApplyAsync(fn)
- 在环境定义的执行程序上运行fn
无论情况如何。对于CompletableFuture
这通常是ForkJoinPool.commonPool()
。thenApplyAsync(fn,exec)
- 在fn
上运行 ---exec
。最终结果是一样的,但调度行为取决于方法的选择。