JUC-5-CountDownLatch 闭锁

 
CountDownLatch 闭锁 同步辅助类
一组操作中,多个线程完成,  闭锁会允许一个或多个线程一直等待.  
即 所有线程都完成才继续执行
 
 
主要方法
CountDownLatch.await();             //等待所有线程(倒计时器) 完成
 
CountDownLatch.countDown();   //倒计时器 数量-1
 
package com.wf.zhang.juc;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch 闭锁 同步辅助类
 * 一组操作中,多个线程完成,  闭锁会允许一个或多个线程一直等待.
 * 即 所有线程都完成才继续执行
 *
 * 场景:5个线程 打印50000以内的偶数 所用的时间
 *
 * 相当于每个线程都有一个倒计时器 (这里都是5个,5个线程5个倒计时器)  所有倒计时都归零是才执行计算时间
 */
public class TestCountDownLatch {

    public static void main(String[] args) {

        final CountDownLatch latch = new CountDownLatch(5);
        LatchDemo ld = new LatchDemo(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("耗费时间为: " + (end - start));
    }
}

class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        synchronized (this) {
            try {
                for (int i = 0; i < 50000; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
            } finally {
                //倒计时器个数-1
                latch.countDown();
            }
        }
    }
}

 

posted @ 2019-12-22 15:47  wf.zhang  阅读(289)  评论(0编辑  收藏  举报