问题描述
假设我有以下代码:
CompletableFuture<Integer> future
= CompletableFuture.supplyAsync( () -> 0);
thenApply
案例:
future.thenApply( x -> x + 1 )
.thenApply( x -> x + 1 )
.thenAccept( x -> System.out.println(x));
这里输出为2.现在是 thenApplyAsync
:
Here the output will be 2. Now in case of thenApplyAsync
:
future.thenApplyAsync( x -> x + 1 ) // first step
.thenApplyAsync( x -> x + 1 ) // second step
.thenAccept( x -> System.out.println(x)); // third step
我在这里读到了每个 thenApplyAsync
在一个单独的线程中执行'同时'(这意味着跟随 thenApplyAsyncs
在之前启动,然后是ApplyAsyncs
完成),如果是这样,输入是什么如果第一步没有完成,第二步的参数值是什么?
I read in this blog that each thenApplyAsync
are executed in a separate thread and 'at the same time'(that means following thenApplyAsyncs
started before preceding thenApplyAsyncs
finish), if so, what is the input argument value of the second step if the first step not finished?
如果第二步没有采取第一步的结果将在哪里?
第三步将采取哪一步结果?
Where will the result of the first step go if not taken by the second step?the third step will take which step's result?
如果第二步必须等待第一步的结果那么异步
?
If the second step has to wait for the result of the first step then what is the point of Async
?
这里x - > x + 1只是为了表明这一点,我想知道的是在非常长的计算。
Here x -> x + 1 is just to show the point, what I want know is in cases of very long computation.
推荐答案
区别与执行者
有关负责运行代码。 CompletableFuture
上的每个运营商通常有3个版本。
The difference has to do with the Executor
that is responsible for running the code. Each operator on CompletableFuture
generally has 3 versions.
-
thenApply(fn)
- 在由CompleteableFuture
定义的线程上运行fn
被调用,所以你通常不知道这将被执行的地方。如果结果已经可用,它可能立即执行。 -
thenApplyAsync(fn)
- 运行fn
在环境定义的执行程序上,无论情况如何。对于CompletableFuture
,这通常是ForkJoinPool.commonPool()
。 -
thenApplyAsync(fn,exec)
- 在exec
上运行fn
。
thenApply(fn)
- runsfn
on a thread defined by theCompleteableFuture
on which it is called, so you generally cannot know where this will be executed. It might immediately execute if the result is already available.thenApplyAsync(fn)
- runsfn
on a environment-defined executor regardless of circumstances. ForCompletableFuture
this will generally beForkJoinPool.commonPool()
.thenApplyAsync(fn,exec)
- runsfn
onexec
.
最后结果相同,但调度行为取决于方法的选择。
In the end the result is the same, but the scheduling behavior depends on the choice of method.
这篇关于Java CompletableFuture的thenApply和thenApplyAsync有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!