CountDownLatch

CountDownLatch是一个同步计数器,初始化的时候传入需要等待执行完成的线程数。

await():阻塞当前线程,等待其他线程执行完成,直达计数器计数值减到0

countDown():负责计算器的减1操作

以下为示例代码:

package com.bc.test;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

    public static void main(String[] args) throws Exception{
        System.out.println("等待子线程执行完毕...");
        final CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(new Runnable() {
            public void run() {
                System.out.println("子线程,"+Thread.currentThread().getName()+"开始执行...");
                countDownLatch.countDown();//每次减去1
                System.out.println("子线程,"+Thread.currentThread().getName()+"结束执行...");
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                System.out.println("子线程," + Thread.currentThread().getName() + "开始执行...");
                countDownLatch.countDown();
                System.out.println("子线程," + Thread.currentThread().getName() + "结束执行...");
            }
        }).start();

        countDownLatch.await();// 调用当前方法主线程阻塞  countDown结果为0, 阻塞变为运行状态
        System.out.println("两个子线程执行完毕....");
        System.out.println("继续主线程执行..");
    }
}

运行结果:

CountDownLatch_第1张图片

 

你可能感兴趣的:(并发编程)