自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java多線程方案如何處理關(guān)鍵代碼

開發(fā) 后端
Java多線程方案需要我們不斷的注意相關(guān)代碼的編寫,下面我們就看看如何才能更好的進(jìn)行學(xué)習(xí)。希望大家在不斷的學(xué)習(xí)中掌握相關(guān)知識(shí)。

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)鍵代碼如下:

 

  1. public<T> voidParallelRecursive(final Executorexec,List<Node<T>>nodes,Collection<T> results){  
  2. for(Node<T> n:nodes){  
  3. exec.execute(new Runnable(){  
  4. public void run(){  
  5. results.add(n.compute());  
  6. }  
  7. });  
  8. parallelRecursive(exec,n.getChildren(),results);  
  9. }  
  10. }  
  11. public<T>Collection<T>getParallelResults(List<Node<T>>nodes)  
  12. throws InterruptedException{  
  13. ExecutorService exec=Executors.newCachedThreadPool();  
  14. Queue<T> resultQueue=newConcurrentLinkedQueue<T>();  
  15. parallelRecursive(exec,nodes,resultQueue);  
  16. exec.shutdown();  
  17. exec.awaitTermination(Long.MAX_VALUE,TimeUnit.SECONDS);  
  18. return reslutQueue;  

 

但是以上程序不能處理不存在任何方案的情況,而下列程序可以解決這個(gè)問題

 

  1. public class PuzzleSolver<P,M>extendsConcurrentPuzzleSolver<P,M>{  
  2. ...  
  3. privatefinal AtomicInteger taskCount=new AtomicInteger(0);  
  4. protectedRunnable newTask(P p,M m,Node<P,M>n){  
  5. return new CountingSolverTask(p,m,n);  
  6. }  
  7. classCountingSolverTask extends SolverTask{  
  8. CountingSolverTask(P pos,Mmove,Node<P,M> prev){  
  9. super(pos,move,prev);  
  10. taskCount.incrementAndGet();  
  11. }  
  12. publicvoid run(){  
  13. try{  
  14. super.run();  
  15. }  
  16. finally{  
  17. if (taskCount.decrementAndGet()==0)  
  18. solution.setValue(null);  
  19. }  
  20. }  
  21. }  

 

以上就是Java多線程方案關(guān)鍵代碼的詳細(xì)介紹。

【編輯推薦】

  1. Java多線程操作相關(guān)問題總結(jié)
  2. 如何理解Java多線程編程的相關(guān)問題
  3. Java多線程信號(hào)量如何控制相關(guān)資源
  4. Java多線程鎖如何進(jìn)行數(shù)據(jù)同步共享
  5. 帶你走進(jìn)Java多線程編程的神秘世界
責(zé)任編輯:張浩 來源: IT168
相關(guān)推薦

2010-03-16 11:05:53

Java while循

2024-08-29 08:54:35

2023-02-02 08:56:25

線程池線程submit

2010-03-15 18:11:38

Java多線程

2010-03-16 14:20:57

Java多線程調(diào)試

2015-11-18 18:56:36

Java多線程處理

2010-03-15 17:56:23

Java多線程

2025-02-04 11:45:23

2017-05-27 20:59:30

Java多線程synchronize

2019-08-15 10:20:19

云計(jì)算技術(shù)安全

2010-03-16 19:46:14

Java線程函數(shù)

2018-06-08 09:12:48

微軟

2011-12-15 12:32:19

JavaNIO

2024-09-26 10:51:51

2009-06-29 18:14:23

Java多線程volatile關(guān)鍵字

2010-03-17 19:24:38

Java多線程循環(huán)

2010-03-17 18:04:55

java Socket

2015-09-01 11:20:58

程序員糟糕代碼

2015-08-31 10:14:30

程序員處理代碼糟糕代碼

2010-03-17 10:53:39

java doc線程
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)