一直苦於沒法控制多線程的處理順序,最近看到java提供了很好的工具,因此抓過來學習下。可是看了一通註釋還有網上的一堆解釋,看的頭暈。仍是寫一個測試代碼來理解好了。java
示例代碼實現了,多個線程處理list加總和的問題。多線程
主要有兩點須要注意:工具
1,經過CyclicBarrier來控制多線程處理流程學習
2,經過synchronized來同步彙總總和測試
package com.thread;this
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;線程
/**
* 模擬多個線程來處理list的數據加和,並最後打出結果
* @author owen.huang
*
*/get
class SumList implements Runnable{
private List<Integer> subList;
private CyclicBarrier barrier;
private Integer subSum = 0;
public static Long allSum = 0l;
private static Object obj = new Object();
public Integer getSubSum() {
return subSum;
}同步
public SumList(List<Integer> subList, CyclicBarrier barrier){
this.subList = subList;
this.barrier = barrier;
}
public void run() {
for(int i=0;i<subList.size();i++){
subSum = subSum + subList.get(i);
}
synchronized(obj){
allSum = allSum + subSum;
}
try {
barrier.await();//要求計算完畢,等待其它線程
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}it
public class TestCyclicbarrier {
public static void main(String[] args){
int threadCounts = 10;//線程數
int num = 100000;
//之因此加1,是爲了控制主線程,讓它等待知道全部線程走完 CyclicBarrier barrier = new CyclicBarrier(threadCounts+1); List<Integer> list = new ArrayList<Integer>(); for(int i=0;i<num;i++){ list.add(i); } int intval = num/threadCounts; for(int i=0;i<threadCounts;i++){ List<Integer> subList = list.subList(intval*i, intval*(i+1)); SumList s = new SumList(subList,barrier); new Thread(s).start(); } try { barrier.await();//要求主線程等待其它線程運行結束 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } System.out.println(SumList.allSum); } }