Introduction of CountDownLatch of JUC-AQS frame synchronization component

What is CountDownLatch?

CountDownLatchJava1.5 is introduced and together with it is introduced into the well tools concurrently CyclicBarrier, Semaphore, ConcurrentHashMapand BlockingQueue, which are present in the java.util.concurrent package. The CountDownLatch class enables a thread to wait for other threads to complete their work before executing. For example, the main thread of the application wants to execute after the thread responsible for starting the framework service has started all framework services.
CountDownLatch is implemented by one 计数器, the initial value of the counter is the number of threads. Whenever a thread completes its task, the counter value will decrease by one. When the counter value reaches 0, it indicates that all threads have completed the task, and then the thread waiting on the lock can resume the execution of the task.

The core point of CountDownLatch is-"await blocks immediately and the countdown count is lifted.

Regarding countDownLatch.await (10, TimeUnit.MILLISECONDS) 可选时间参数, there is an additional blocking cancellation condition, when the count reaches 0 and the time reaches 0, one of the conditions is met and the blocking waiting thread can be released.

You can run this little demo,
package com.bestksl.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CountDownLatchExample2 {

    static final int clientTotal = 500;  //并发总计数
    static final int threadTotal = 20;   //并发线程最大值


    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        Semaphore semaphore = new Semaphore(threadTotal);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < clientTotal; i++) {
            final int n = i;
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    p(n);
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info(e.getMessage());
                } finally {
                    countDownLatch.countDown();  // 因为只是示范, 所以放到了finally中保证计数, 如有特殊情况应该加入处理逻辑
                }
            });
        }

        executorService.execute(() -> {
            try {
                countDownLatch.await(10, TimeUnit.MILLISECONDS);// 加上时间参数可以强行到时激活await()
                System.out.println("done");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        executorService.shutdown();
    }

    //并发方法
    private static void p(int n) throws InterruptedException {
        Thread.sleep(200);
        log.info(n + "");
        Thread.sleep(200);
    }
}
Published 248 original articles · praised 416 · 90,000 views +

Guess you like

Origin blog.csdn.net/qq_33709508/article/details/105463912