并行执行callables

Dän*_*änu 3 java multithreading callable

我想并行执行多个callables.但看起来ExecutorService总是等到所有的callables完成.

我尝试过以下方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

现在,当完成executorService中的所有可调用对象时,将调用for循环.据我所知,没有executorService.isParallel setter ;-).

让callables并行的正确方法是什么?

谢谢你的提示!

Qwe*_*rky 9

invokeAll的javadoc 说;

执行给定的任务,返回完成所有状态和结果的Futures列表.对于返回列表的每个元素,Future.isDone()都为true.

因此invokeAll阻塞直到集合中的每个任务完成.


Van*_*ran 5

Executor服务并行运行所有可调用项.它所做的就是等待所有并行任务在继续之前完成.所以它不像所有任务都是串行运行的.