问题描述
CompletableFuture<ResponseList> stsTask = CompletableFuture.supplyAsync(() -> this.stsCompute(question);
CompletableFuture<ResponseList> dssmTask = CompletableFuture.supplyAsync(() -> this.dssmCompute(question);
// Is this line unnecessary?
CompletableFuture<Void> twoFutures = CompletableFuture.allOf(stsTask, dssmTask);
try {
ResponseList stsList = stsTask.get();
ResponseList dssmList = dssmTask.get();
// after the two are done, proceed here
processResult(stsList, dssmList)
} catch(Exception e){
// do something
}
我有两个问题:
- 这两个任务是否同时执行?或者由于<$ c,必须在dssmTask之前执行stsTask $ c> get()方法等待其完成吗?不使用变量'twoFutures'。
- 行
CompletableFuture .allOf(stsTask,dssmTask)
不必要或必要sary?
- Are these two tasks executed concurrently? Or the stsTask must be executed before dssmTask due to the
get()
method to wait it for completion? The variable 'twoFutures' is not used. - Is the line
CompletableFuture.allOf(stsTask, dssmTask)
unnecessary or necessary?
推荐答案
是的,如果您在普通fork中有足够的线程,它们将同时执行加入游泳池。 allOf
方法返回一个新的 CompletableFuture
,当所有给定的 CompletableFutures 完成时,该新的完成。 code>完成。但是您没有任何合并结果的工具,因此这里不需要。
Yes they are executed concurrently if you have enough threads in your common fork/join pool. The allOf
method returns a new CompletableFuture
that is completed when all of the given CompletableFutures
complete. But you don't get any facility to merge the result, hence it is not needed here.
这里要考虑的另一点是调用 future.get()
方法即可获取结果。此方法调用处于阻塞状态,将使您的调用线程保持阻塞状态。
Another point to consider here is that the invocation of future.get()
method to get the result. This method call is blocking and will keep your calling thread in blocking state.
所以这是一种更好的方法,
So here's a better way of doing it,
stsTask.thenCombine(dssmTask, (stsList, dssmList) -> processResult(stsList, dssmList));
这篇关于这两个任务是否同时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!