JUC--闭锁 CountDownLatch

CountDownLatch是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,允许一个或者多个线程一直等待。

闭锁可以延迟线程的进度直到其到达终止状态,可以确保某些活动知道其他活动都完成才继续执行

注意:在run方法中必须将调用countdown方法 计数减1 并且在new CountDownLatch时创建的个数要和for循环中的线程个数相等,并且调用latch.await()方法进行等到所有的thread执行完毕。

应用场景:

  例如 超市中多个线程计算每个种类的商品的信息 ,使用countdownlatch等到各个种类的信息计算完之后,统计总信息。

/**
 * countdownlatch 闭锁 在完成某些运算时,只有其他所有thread得运算全部完成 当前运算才能继续执行
 */
public class TestCountDownLatch {
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(5);
        CDLDemo ld= new CDLDemo(latch);
        long start =System.currentTimeMillis();
        for(int i=0;i<5;i++){
            new Thread(ld).start();
        }
        try{
            latch.await();
        }catch (InterruptedException e){
        }
        long end = System.currentTimeMillis();
        System.out.println("use time:================"+(end-start));
    }
}

class CDLDemo implements Runnable {
    private CountDownLatch latch;
     CDLDemo(CountDownLatch latch) {
        this.latch = latch;
    }




    @Override
    public void run() {
        synchronized (this){
            try{
                for(int i=0;i<500;i++){
                    if(i%2==0)
                        System.out.println(i);
                }
            }finally {

                latch.countDown();
            }

        }



    }
}

猜你喜欢

转载自www.cnblogs.com/zhy-study/p/9398960.html
今日推荐