Java多線程方案如何處理關(guān)鍵代碼
Java多線程方案在不斷的完善中已經(jīng)找到了自己的各種缺點(diǎn),下面我們就來看看如何才能更好的學(xué)習(xí)相關(guān)問題。希望大家在不斷的學(xué)習(xí)中有所收獲,自由在不斷的學(xué)習(xí)中才能更好的進(jìn)行掌握J(rèn)ava多線程方案。
1、當(dāng)每個(gè)迭代彼此獨(dú)立,并且完成循環(huán)體中每個(gè)迭代的工作,意義都足夠重大,足以彌補(bǔ)管理一個(gè)新任務(wù)的開銷時(shí),這個(gè)順序循環(huán)是適合并行化的。
2、Java多線程方案關(guā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;
- }
但是以上程序不能處理不存在任何方案的情況,而下列程序可以解決這個(gè)問題
- 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);
- }
- }
- }
- }
以上就是Java多線程方案關(guān)鍵代碼的詳細(xì)介紹。
【編輯推薦】