gpt4 book ai didi

java - 如何调整这3个线程的控制流程?

转载 作者:行者123 更新时间:2023-11-30 02:00:42 27 4
gpt4 key购买 nike

// Task 1 -- the main thread
SimilarityResponse w2vResponse = questionClassifier.compute(questionInfo);

// Task 2
String sku = questionInfo.getSku();
String question = questionInfo.getQuestion();
Callable<ResponseList> dssmTask = () -> this.dssmCompute(sku, question);
Future<ResponseList> dssmService = executorService.submit(dssmTask);
ResponseList dssmResponse;
try {
LOGGER.info("start dssm ... {} ", question);
dssmResponse = dssmService.get(Parameters.getParserTimeLimit(), TimeUnit.MILLISECONDS);
LOGGER.info("dssmResponse ... {} ", dssmResponse);
} catch (ExecutionException | InterruptedException e) {
LOGGER.warn("ExecutionException | InterruptedException");
e.printStackTrace();
} catch (TimeoutException te) {
dssmService.cancel(true);
LOGGER.warn("DSSM time out for {} {}", sku, question);
}

// Task 3
Callable<ResponseList> stsTask = () -> this.stsCompute(sku, question);
Future<ResponseList> stsService = executorService.submit(stsTask);
ResponseList stsResponse;
try {
LOGGER.info("start sts ... {} ", question);
stsResponse = stsService.get(Parameters.getParserTimeLimit(), TimeUnit.MILLISECONDS);
LOGGER.info("stsResponse ... {} ", stsResponse);
} catch (ExecutionException | InterruptedException e) {
LOGGER.warn("ExecutionException | InterruptedException");
e.printStackTrace();
} catch (TimeoutException te) {
stsService.cancel(true);
LOGGER.warn("STS time out for {} {}", sku, question);
}

// Last step == do something for above
SimilarityResponse ensemble = new SimilarityResponse();
return ensemble;

在执行最后一步之前,如何确保任务1-3已经完成?目前的代码看起来是先完成Task 1然后直接返回。

最佳答案

您应该使用 CountDownLatch。在主线程中创建它的实例并将该实例传递给您的任务(Callables)。然后当任务完成时调用latch.countDown()。在代码的最后一步中,调用latch.await() 来等待每个任务完成。它看起来像这样(如果您的可调用对象是作为 lambda 创建的):

final CountDownLatch latch = new CountDownLatch(3);

for(int x = 0; x < 3; x++) {
service.submit( () -> {
// do something
latch.countDown();
});
}

// in the end wait for tasks to finish
latch.await();

关于java - 如何调整这3个线程的控制流程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938231/

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