我想并行执行多个可调用对象。但似乎 ExecutorService 总是等到所有可调用对象都完成。
我尝试了以下方法:
final int nThreads = 10;
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);
List<PrimeCallable> tasks = new ArrayList<PrimeCallable>();
for(int i = 0; i < nThreads; i++) {
tasks.add(new PrimeCallable(0, i * 100 + 100, "thread" + i));
}
try {
for(Future<List<Integer>> result : executorService.invokeAll(tasks)) {
List<Integer> integers = result.get();
for(Integer i : integers){
System.out.println(i);
}
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在,当 executorService 中的所有可调用对象都完成时,将调用 for 循环。据我所知,没有 executorService.isParallel setter ;-)。
让可调用对象并行运行的正确方法是什么?
感谢您的提示!