java-通过多线程展开并行递归计算

1、当每个迭代彼此独立,并且完成循环体中每个迭代的工作,意义都足够重大,足以弥补管理一个新任务的开销时,这个顺序循环是适合并行化的。

2、

public voidParallelRecursive(final Executorexec,List>nodes,Collection results){

    for(Node n:nodes){

      exec.execute(new Runnable(){

             public void run(){

                 results.add(n.compute());

             }

      });

       parallelRecursive(exec,n.getChildren(),results);

    }

}

publicCollectiongetParallelResults(List>nodes)

    throws InterruptedException{

      ExecutorService exec=Executors.newCachedThreadPool();

      Queue resultQueue=newConcurrentLinkedQueue();

      parallelRecursive(exec,nodes,resultQueue);

      exec.shutdown();

      exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);

      return reslutQueue;

}

但是以上程序不能处理不存在任何方案的情况,而下列程序可以解决这个问题

public class PuzzleSolverextendsConcurrentPuzzleSolver{

    ...

    privatefinal AtomicInteger taskCount=new AtomicInteger(0);

   

    protectedRunnable newTask(P p,M m,Noden){

       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);

          }

       }

    }

}

 

你可能感兴趣的:(解释语言)