package net.biancheng.c.thread;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author cheng
* @Description 统计所有线程的数字汇总
* @Date 2022/8/29 17:29
*/
public class Caculate {
public static List<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
int nums = 15;
ExecutorService executor = Executors.newFixedThreadPool(nums);
CyclicBarrier barrier = new CyclicBarrier(nums, () -> {
try {
System.out.println("Arrays.toString(list.toArray()) = " + Arrays.toString(list.toArray()));
Integer total = 0;
for (int i = 0; i < list.size(); i++) {
total = total + list.get(i);
}
System.out.println("total = " + total);
} catch (Exception e) {
e.printStackTrace();
}
});
for (int i = 0; i < nums; i++) {
executor.submit(new Each(barrier, (i + 1)));
}
executor.shutdown();
}
static class Each implements Runnable {
private CyclicBarrier barrier;
private Integer nums;
private static final ReentrantLock lock = new ReentrantLock();
public Each(CyclicBarrier barrier, Integer nums) {
this.barrier = barrier;
this.nums = nums;
}
@Override
public String toString() {
return "Each{" +
"barrier=" + barrier +
", nums=" + nums +
'}';
}
@Override
public void run() {
try {
//必须同步,不然nums可能为空;
/* synchronized(Each.class){
list.add(nums);
}*/
lock.lock();
list.add(nums);
lock.unlock();
System.out.println(Thread.currentThread().getName() + ",nums = " + nums);
barrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}