gpt4 book ai didi

java - 我需要用主线程来控制这两个线程的执行吗?

转载 作者:行者123 更新时间:2023-11-30 05:56:09 25 4
gpt4 key购买 nike

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);
}

在这个“process”方法中,我有两个额外的线程“callable1”和“callable2”来并发执行。我想确保只有当这两个任务完成时,主线程“processResponse()”中的方法才能开始执行。

在这种情况下,我是否需要添加任何额外的控制来保证执行的顺序,是否已经足够好了?如果没有,如何实现这种控制?

最佳答案

您应该使用 ExecutorService.invokeAll ,它将在完成时返回 Future 列表。此外,我会使用更短的语法,例如

 List<Future> futures = executorService.invokeAll(Arrays.asList(()->dssmCompute(), ()->dssmCompute()));

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com