3 回答

TA贡献1866条经验 获得超5个赞
在你的代码提交Callable到ExecutorService由一个一个,马上招呼Future.get(),这将阻止,直到结果准备好(或异常是在运行时抛出)。
你最好ExecutorService用CompletionSerivce它来包装,一旦它们准备好就提供结果。并将 for 循环拆分为两个循环:一个提交所有Callables,第二个检查结果。
ExecutorService es = Executors.newFixedThreadPool(4);
ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(es);
for (CallableImpl callableImpl : callList) {
System.out.println("Trying to connect to: " + callableImpl.getUrl());
completionService.submit(callableImpl);
}
for (int i = 0; i < callList.size(); ++i) {
completionService.take().get(); //fetch next finished Future and check its result
}
添加回答
举报