java并发初探CountDownLatch

java并发初探CountDownLatch

CountDownLatch是同步工具类能够允许一个或者多个线程等待直到其他线程完成操作。
当前前程A调用CountDownLatch的await方法进入阻塞(LockSupportd的park方法),
其他线程调用CountDownLatch调用countDown(),CountDownLatch的内部变量
count为零时,线程A唤醒。

 * A synchronization aid that allows one or more threads to wait until
 * a set of operations being performed in other threads completes.
 *

例子

package com.java.javabase.thread.base.concurrent.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;

/**
 * @author
 */
@Slf4j
public class CountDownLatchTest {
    private static CountDownLatch countDownLatch = new CountDownLatch(5);

    public static void main(String[] args) {
        new Thread() {
            @Override
            public void run() {
                try {
                    log.info("thread {} call wait ",Thread.currentThread().getName());
                    sleep(1000);
                    countDownLatch.await();
                    log.info("thread {} end ",Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        for (int i = 0; i < 5; i++) {
            new Thread() {
                @Override
                public void run() {
                    log.info("thread {} run ",Thread.currentThread().getName());
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    countDownLatch.countDown();
                }
            }.start();
        }
        log.info("current thread is {}",Thread.currentThread().getName());
        try {
            countDownLatch.await();
            log.info("thread is {} end",Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

例子结果

2019-08-09 17:40:10,492   [Thread-1] INFO  CountDownLatchTest  - thread Thread-1 run 
2019-08-09 17:40:10,492   [Thread-3] INFO  CountDownLatchTest  - thread Thread-3 run 
2019-08-09 17:40:10,492   [Thread-2] INFO  CountDownLatchTest  - thread Thread-2 run 
2019-08-09 17:40:10,492   [Thread-0] INFO  CountDownLatchTest  - thread Thread-0 call wait 
2019-08-09 17:40:10,492   [main] INFO  CountDownLatchTest  - current thread is main
2019-08-09 17:40:10,492   [Thread-4] INFO  CountDownLatchTest  - thread Thread-4 run 
2019-08-09 17:40:10,492   [Thread-5] INFO  CountDownLatchTest  - thread Thread-5 run 
2019-08-09 17:40:11,491   [main] INFO  CountDownLatchTest  - thread is main end
2019-08-09 17:40:11,491   [Thread-0] INFO  CountDownLatchTest  - thread Thread-0 end 
原文地址:https://www.cnblogs.com/JuncaiF/p/11328754.html