JUC学习之CountDownLatch

package countDownLatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,
 * 每调用一次countDown()方法,计数器减1,计数器大于0 时,
 * await()方法会阻塞程序继续执行
 * */
public class CountDownLatchTest {
    //启动多个线程,多线程汇总二维数组每行的结果,然后汇总所有结果
    private int[][] data = new int[][] { { 1, 3, 5, 7, 9 }, { 2, 4, 6, 8, 10 } };
    private CountDownLatch countLatch;
    
    public CountDownLatchTest() throws InterruptedException{
        //汇总数
        int total = 0;
        List<MyCaculate> threadList = new ArrayList<MyCaculate>();
        // 启动二维数组行数个线程
        int threadCount = data.length;
        countLatch = new CountDownLatch(threadCount);
        for(int i=0;i<threadCount;i++){
            MyCaculate caculate = new MyCaculate(data[i],countLatch);
            caculate.setName("caculate-thread-"+i);
            caculate.start();
            //System.out.println(caculate.isDone());
            threadList.add(caculate);
        }
        //阻塞所有线程计算完成
        countLatch.await();
        //
        for(MyCaculate c:threadList){
            /*while(true){
                if(c.isDone()){
                    total+=c.getSum();
                    break;
                }
            }*/
            //因为上面await会阻塞到所有线程完成,所以,不用判断isDone
            total+=c.getSum();
        }
        System.out.println("--------------------------------------");
        System.out.println("各行汇总结果操作完成,汇总结果:"+total);
    }
    
    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        CountDownLatchTest c = new CountDownLatchTest();
    }

}
class MyCaculate extends Thread
{
    private CountDownLatch countLatch;
    private int[] row;
    private int sum;
    private boolean isDone = false;
    
    public MyCaculate(int[] row,CountDownLatch countLatch){
        this.row = row;
        this.countLatch = countLatch;
    }
    
    @Override
    public void run() {
        
        try {
            System.out.println(Thread.currentThread().getName()+" 开始计算");
            for(int i:row){
                sum+=i;
            }
        }finally{
            //做完,计数器减1
            countLatch.countDown();
        }
        isDone = true;
    }
    public int getSum(){
        return sum;
    }
    public boolean isDone(){
        return isDone;
    }
}

可以比较一下和CyclicBarrier的区别,Barrier是阻塞的地方,在每个具体的线程,而CountDownLatch,阻塞在节点上。搞得CountDownLatch反而有点关卡的意思。

你可能感兴趣的:(JUC学习之CountDownLatch)