[英]Do I need to control the execution of these two threads with the main threads?
void process(String question){
Callable<ResponseList> callable1 = () -> this.stsCompute question);
Future<ResponseList>task1 = executorService.submit(callable1);
Callable<ResponseList> callable2 = () -> this.dssmCompute(question);
Future<ResponseList>task2 = executorService.submit(callable2);
try{
ResponseList stsResponse = task1.get();
ResponseList dssmResponse = task2.get();
}catch (Exception e){
e.printStackTrace();
}
// Do I need to wait until the first 2 threads complete?
processResponse(stsResponse, dssmResponse);
}
在这个“进程”方法中,我有两个额外的线程“callable1”和“callable2”可以同时执行。 我想确保只有当这两个任务完成时,主线程“processResponse()”中的方法才能开始执行。
在这种情况下,我是否需要添加任何额外的控件来确保执行的顺序,是否已经足够好? 如果没有,如何进行这种控制?
您应该使用 ExecutorService.invokeAll ,它会在完成时返回期货列表。 此外我会使用更短的语法,比如
List<Future> futures = executorService.invokeAll(Arrays.asList(()->dssmCompute(), ()->dssmCompute()));
对于 Java8+,我建议使用 Completable Futures。 它完全支持您尝试实现的用例。
可完成的期货: Java 8
示例算法如下所示:
var cf = CompletableFuture.supplyAsync(() -> processQuestion()).runAsync(() -> processResponse)
注意: var 是 java 10+ 中的 typeInference 支持
此外,Completable Futures 有很多例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.