1、当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。
2、
public<T> voidParallelRecursive(final Executorexec,List<Node<T>>nodes,Collection<T> results){
for(Node<T> n:nodes){
exec.execute(new Runnable(){
public void run(){
results.add(n.compute());
}
});
parallelRecursive(exec,n.getChildren(),results);
}
}
public<T>Collection<T>getParallelResults(List<Node<T>>nodes)
throws InterruptedException{
ExecutorService exec=Executors.newCachedThreadPool();
Queue<T> resultQueue=newConcurrentLinkedQueue<T>();
parallelRecursive(exec,nodes,resultQueue);
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);
return reslutQueue;
}
但是以上程序不能处理不存在任何方案的情况,而下列程序可以解决这个问题
public class PuzzleSolver<P,M>extendsConcurrentPuzzleSolver<P,M>{
...
privatefinal AtomicInteger taskCount=new AtomicInteger(0);
protectedRunnable newTask(P p,M m,Node<P,M>n){
return new CountingSolverTask(p,m,n);
}
classCountingSolverTask extends SolverTask{
CountingSolverTask(P pos,Mmove,Node<P,M> prev){
super(pos,move,prev);
taskCount.incrementAndGet();
}
publicvoid run(){
try{
super.run();
}
finally{
if (taskCount.decrementAndGet()==0)
solution.setValue(null);
}
}
}
}
本文介绍了一种基于递归的并行计算方法,通过创建并行任务来加速计算过程。这种方法适用于各迭代间相互独立并且每个迭代都有重大计算意义的情况。文章还提供了一个能够处理所有情况的改进版本。
495

被折叠的 条评论
为什么被折叠?



