Java多線程循環(huán)相關(guān)的代碼介紹
作者:佚名
Java多線程循環(huán)如何才能更好的進行相關(guān)問題的解決。下面我們就來看看如何才能更好的進行源代碼的使用。希望大家有所收獲。
Java多線程循環(huán)需要我們不斷的學習,有很多的問題一直是我們相互關(guān)心的。下面我們就來看看如何才能更好的使用這門編程語言。當每個迭代彼此獨立,并且完成循環(huán)體中每個迭代的工作,意義都足夠重大,足以彌補管理一個新任務的開銷時,這個順序循環(huán)是適合并行化的。
- 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>extendsConcurrent
PuzzleSolver<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);
- }
- }
- }
- }
以上就是對Java多線程循環(huán)的相關(guān)介紹。希望大家有所收獲。
【編輯推薦】
責任編輯:張浩
來源:
互聯(lián)網(wǎng)