闭锁——CountDownLatch类

代码演示说明

import java.util.concurrent.CountDownLatch;
/**
 * CountDownLatch(倒计时闩锁)
 * 闭锁:在完成某些运算时,只有其他所有线程的运算全部完成,当前运算才继续执行
 * 如:多个辅线程计算不同资源,每个辅线程会得到一个结果,再由一个主线程将多个辅线程的结果汇总。
 */
public class CountDownLatchDemo {
    public static void main(String[] args)  {
        //初始线程闭锁为10个
        CountDownLatch cdl = new CountDownLatch(10);
        CDLTest cdlTest = new CDLTest(cdl);
        long start = System.currentTimeMillis();
        //开启是个线程
        for (int i = 0; i < 10; i++) {
            new Thread(cdlTest).start();
        }
        
        //如果线程没执行完,主线程挂起等待,其他线程执行完。
        try {
            cdl.await();
        } catch (InterruptedException e) {        }
        //闭锁为0时计算这些线程耗费的时间。
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }
}

class CDLTest implements Runnable {
    private final CountDownLatch cd;
    private int sum = 0;
    public CDLTest(CountDownLatch cd) {
        this.cd = cd;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 50000; i++) {
                    if (i % 10000 == 0) {
                        try { Thread.sleep(10); } catch (InterruptedException e) { }
                    }
                    sum+=i;
                }
                System.out.println(Thread.currentThread().getName()+"  "+sum);
            }finally {//必须执行的程序用finally包裹
                sum=0;
                //线程计数器,执行完一个线程减减一个线程
                cd.countDown();
            }
        }
    }
}
发布了51 篇原创文章 · 获赞 20 · 访问量 1546

猜你喜欢

转载自blog.csdn.net/qq_39711439/article/details/101462363