1、当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。
2、
public
for(Node
exec.execute(new Runnable(){
public void run(){
results.add(n.compute());
}
});
parallelRecursive(exec,n.getChildren(),results);
}
}
public
throws InterruptedException{
ExecutorService exec=Executors.newCachedThreadPool();
Queue
parallelRecursive(exec,nodes,resultQueue);
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);
return reslutQueue;
}
但是以上程序不能处理不存在任何方案的情况,而下列程序可以解决这个问题
public class PuzzleSolver
extendsConcurrentPuzzleSolver
{
...
privatefinal AtomicInteger taskCount=new AtomicInteger(0);
protectedRunnable newTask(P p,M m,Node
n){
return new CountingSolverTask(p,m,n);
}
classCountingSolverTask extends SolverTask{
CountingSolverTask(P pos,Mmove,Node
prev){
super(pos,move,prev);
taskCount.incrementAndGet();
}
publicvoid run(){
try{
super.run();
}
finally{
if (taskCount.decrementAndGet()==0)
solution.setValue(null);
}
}
}
}