gpt4 book ai didi

java - 无法从并发 CompletionService 获取结果

转载 作者:行者123 更新时间:2023-12-01 18:17:40 25 4
gpt4 key购买 nike

我对 Java 并发包非常陌生。我使用 java.util.concurrent.CompletionService 类从池中获取结果,而无需等待其他线程完成任务。但即使执行了 10 分钟的代码,我也无法获取任务。我只是在任务中打印线程名称。这是我的代码。

public class CompletionService {

public void execute(ThreadPoolExecutor argThreadPoolExecutor)
throws InterruptedException, ExecutionException {
java.util.concurrent.CompletionService<String> completionService =
new ExecutorCompletionService<String>(argThreadPoolExecutor);
int counter = 0;
for (int i = 0; i < 4; i++) {
Task task = new Task();
completionService.submit(task);
++counter;
}
print(counter, completionService);
}

private void print(int argCounter,
java.util.concurrent.CompletionService<String> argCompletionService)
throws InterruptedException, ExecutionException {
String s = argCompletionService.take().get();
if (s != null && !s.isEmpty()) {
System.out.println(s);
}
}

public static void main(String[] args) throws InterruptedException,
ExecutionException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8, 8,
3000, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
CompletionService completionService = new CompletionService();
completionService.execute(threadPoolExecutor);
threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
}

任务类别:

public class Task implements Callable<String> {

@Override

public String call() throws Exception {
String name = Thread.currentThread().getName();
return name;
}
}

结果:pool-1-thread-1

我只得到一个线程信息。我等了 10-15 分钟仍然没有得到结果。我有什么地方说错了吗?谁可以帮我这个事。?

感谢。

最佳答案

completionService.execute(threadPoolExecutor);
threadPoolExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

你将永远阻塞在这里,因为你没有向ThreadPoolExecutor请求shutdown .

关于java - 无法从并发 CompletionService 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28743428/

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