新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Java多線程方案如何處理關(guān)鍵代碼
Java多線程方案在不斷的完善中已經(jīng)找到了自己的各種缺點(diǎn),下面我們就來(lái)看看如何才能更好的學(xué)習(xí)相關(guān)問(wè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
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);
- }
- }
- public
Collection getParallelResults(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;
- }
但是以上程序不能處理不存在任何方案的情況,而下列程序可以解決這個(gè)問(wèn)題
- 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);
- }
- }
- }
- }
以上就是Java多線程方案關(guān)鍵代碼的詳細(xì)介紹。
【編輯推薦】
- Java多線程操作相關(guān)問(wèn)題總結(jié)
- 如何理解Java多線程編程的相關(guān)問(wèn)題
- Java多線程信號(hào)量如何控制相關(guān)資源
- Java多線程鎖如何進(jìn)行數(shù)據(jù)同步共享
- 帶你走進(jìn)Java多線程編程的神秘世界
標(biāo)題名稱:Java多線程方案如何處理關(guān)鍵代碼
網(wǎng)站鏈接:http://m.fisionsoft.com.cn/article/dhccgee.html


咨詢
建站咨詢
