1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public void sequencialRecursive(List<Node> nodes, Collection results) {
for (Node n : nodes) {
results.add(node.compute());
sequencialRecursive(n.getChildren(), results);
}
}
public void parallelRecursive(final Executor exec,
List<Node> nodes,
final Collection results) {
for (Node n : nodes) {
exec.submit(() -> results.add(n.compute()));
parallelRecursive(exec, n.getChildren(), results);
}
}
public Collection getParallelResults(List<Node> nodes) throws InterruptedException {
ExecutorService exec = Executors.newCachedThreadPool();
Queue resultQueue = new ConcurrentLinkedQueue();
parallelRecursive(exec, nodes, resultQueue);
exec.shutdown();
// 等到所有任务执行完毕
exec.awaitTermination(Long.MAX_VALUE, TimeUnits.SECONDS);
return resultQueue;
}
|
评论