CyclicBarrier的作用是拦截多个线程,当所有线程到达指定位置时,在开始往下面执行,否则线程等待。
两种构造函数:
public CyclicBarrier(int parties)
public CyclicBarrier(int parties, Runnable barrierAction)
其中parties是线程个数,barrierAction是所有线程到达后执行的任务。
多线程数组求和,首先对数组进行分段,每段一个线程进行求和,当所有线程都完成计算后,在barrierAction中进行整体求和。
public class CyclicBarrierTest implements Runnable {
CyclicBarrierTest(int count) {
this.count = count;
cyclicBarrier = new CyclicBarrier(count, this);
executorService = Executors.newFixedThreadPool(count);
}
private Map<String, Integer> sumMap = new HashMap<>();
private int count = 4;
private CyclicBarrier cyclicBarrier;
private ExecutorService executorService;
public void sum(int[] arr) {
int size = arr.length;
int batch = size / count + 1;
for (int i = 0; i < count; i++) {
int end;
int start;
start = i * batch;
end = Math.min(start + batch, size);
System.out.println(start + " " + end);
executorService.execute(new Calculator(arr, start, end));
}
executorService.shutdown();
}
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
CyclicBarrierTest cyclicBarrierTest = new CyclicBarrierTest(5);
cyclicBarrierTest.sum(arr);
}
class Calculator implements Runnable {
private int[] arr;
private int start;
private int end;
Calculator(int[] arr, int start, int end) {
this.arr = arr;
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for (int i = start; i < end; i++) {
sum += arr[i];
}
sumMap.put(Thread.currentThread().getName(), sum);
try {
// 线程等待,当所有线程都到此处时在往下面执行
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
long sum = sumMap.values().stream().reduce(Integer::sum).get();
System.out.println(sum);
}
}