gpt4 book ai didi

java - 如何在没有特定顺序的情况下管理多个可调用线程结果?

转载 作者:行者123 更新时间:2023-12-01 20:21:58 25 4
gpt4 key购买 nike

基本上是这样的:

ExecutorService service = Executors.newFixedThreadPool(2);

Future<Boolean> futureFoo = service.submit(myFooTask);
Future<Boolean> futureBar = service.submit(myBarTask);

int resultFoo;
boolean resultBar;
resultFoo = futureFoo.get();
resultBar = futureBar.get();

我想做一个事件来独立管理我得到的第一个结果,而不是等待 futureFoo 先完成。

最佳答案

您可以使用CompletionService。可调用的结果被放入队列中,您可以在任务完成后立即获取结果。

在这种情况下,如果 Bar 提前完成,则无需等待 Foo 的结果。

例如:

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CompletionServiceExample {


private static Logger LOGGER = Logger.getLogger("CompletionServiceExample");

public static void main(String[] args) throws InterruptedException {

CompletionServiceExample completionServiceExample = new CompletionServiceExample();
completionServiceExample.doTheWork();
}

private void doTheWork() throws InterruptedException {

final ExecutorService executorService = Executors.newFixedThreadPool(2);
final CompletionService<Boolean> completionService = new ExecutorCompletionService<>(executorService);


completionService.submit(new Foo());
completionService.submit(new Bar());

int total_tasks = 2;

for(int i = 0; i < total_tasks; ++i) {

try {
final Future<Boolean> value = completionService.take();
System.out.println("received value: " + value.get());
} catch (ExecutionException e) {
LOGGER.log(Level.WARNING, "Error while processing task. ", e);
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING, "interrupted while waiting for result", e);
}
}


executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);

}
}

class Foo implements Callable<Boolean> {

@Override
public Boolean call() throws Exception {
Thread.sleep(5000);
return true;
}
}

class Bar implements Callable<Boolean> {

@Override
public Boolean call() throws Exception {
Thread.sleep(1000);
return false;
}
}

关于java - 如何在没有特定顺序的情况下管理多个可调用线程结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578505/

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