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()”中的方法才能开始执行。

在这种情况下,我是否需要添加任何其他控件以确保执行顺序,是否已经足够好?如果没有,该如何进行控制?

最佳答案

对于Java8 +,我建议使用Completable Futures。它完全支持您要实现的用例。

可成交的期货:Java 8

示例算法如下所示:

var cf = CompletableFuture.supplyAsync(()-> processQuestion())。runAsync(()-> processResponse)

注意:var是Java 10+中的typeInference支持

此外,还有很多关于可完成期货的例子

关于java - 我是否需要使用主线程来控制这两个线程的执行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53134840/

10-11 23:08
查看更多