current position:Home>AQS synchronization component - CountDownLatch analysis and case

AQS synchronization component - CountDownLatch analysis and case

2022-08-06 18:29:17share a drink

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情

CountDownLatch原理

CountDownLatch是通过一个计数器来实现的,计数器的初始化值为线程的数量.每当一个线程完成了自己的任务后,计数器的值就相应得减1.当计数器到达0时,表示所有的线程都已完成任务,然后在闭锁上等待的线程就可以恢复执行任务.CountDownLatchCan play a blocking thread,And ensure that the thread continues to execute after a certain condition is met. image.png

CountDownLatch 的两种典型用法

  • 某一线程在开始运行前等待n个线程执行完毕.将 CountDownLatch 的计数器初始化为n :new CountDownLatch(n),每当一个任务线程执行完毕,就将计数器减1 countdownlatch.countDown(),当计数器的值变为0时,在CountDownLatch上 await()的线程就会被唤醒.一个典型应用场景就是启动一个服务时,主线程需要等待多个组件加载完毕,之后再继续执行.That is, through initialization,定义线程个数.
  • 实现多个线程开始执行任务的最大并行性.注意是并行性,不是并发,强调的是多个线程在某一时刻同时开始执行.类似于赛跑,将多个线程放到起点,等待发令枪响,然后同时开跑.做法是初始化一个共享的 CountDownLatch 对象,将其计数器初始化为 1 :new CountDownLatch(1),多个线程在开始执行任务前首先 coundownlatch.await(),当主线程调用 countDown() 时,计数器变为0,多个线程同时被唤醒.

源码分析

/** * 构造器中的计数值(count)实际上就是闭锁需要等待的线程数量.这个值只能被设置一次, *而且CountDownLatch没有提供任何机制去重新设置这个计数值. * * @param count The thread can pass {@link #await} 之前必须调用 {@link #countDown} 的次数 * @throws IllegalArgumentException If the given parameter is less than0则抛出异常 */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
复制代码
/** * 使当前线程等待,直到计数器为零,除非当前线程被中断 * 1.The current count is zero,则此方法立即返回 * 2.如果当前计数大于零,则当前线程将因线程调度目的而被禁用并处于休眠状态, * until the following may occur: * 由于调用了 {@link #countDown} 方法,计数达到零 * Thread waiting to be interrupted. * @throws 如果当前线程在等待时被中断 */
    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
复制代码
/** * 可以设置等待时间,It will be executed after this time,Does not wait until the counter becomes0,但是 * The previously given thread will still be executed * * @param timeout waiting time length * @param unit 等待时间单位 * @return * @throws 如果当前线程在等待时被中断 */
public boolean await(long timeout, TimeUnit unit)
    throws InterruptedException {
    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
复制代码

与CountDownLatch的第一次交互是主线程等待其他线程.主线程必须在启动其他线程后立即调用CountDownLatch.await()方法.这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务. 其他N 个线程必须引用闭锁对象,因为他们需要通知CountDownLatch对象,他们已经完成了各自的任务.这种通知机制是通过 CountDownLatch.countDown()方法来完成的;每调用一次这个方法,在构造函数中初始化的count值就减1.所以当N个线程都调用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务. 注意:

  • CountDownLatch的构造函数 CountDownLatch countDownLatch = new CountDownLatch(7); //7Indicates the number of threads to wait for execution to complete.
  • After each thread has finished executing,都需要执行 countDownLatch.countDown() 方法,Otherwise the counter will not be accurate;
  • Only after all threads are executed,才会执行 countDownLatch.await() 之后的 代码;
  • CountDownLatch 阻塞的是主线程;

CountDownLatch 的使用示例

@Slf4j
public class CountDownLatchExample1 {
    /** * 线程数量 */
    private final static int threadCount = 200;

    public static void main(String[] args) throws Exception {

        ExecutorService exec = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            exec.execute(() -> {
                try {
                    test(threadNum);
                } catch (Exception e) {
                    log.error("exception", e);
                } finally {
                    // Indicates that a request has completed
                    countDownLatch.countDown();
                }
            });
        }
        //使当前线程等待,直到计数器为零,除非当前线程被中断
        countDownLatch.await();
        //当这200个请求被处理完成之后,才会执行
        log.info("finish");
        exec.shutdown();
    }

    private static void test(int threadNum) throws Exception {
        // 模拟请求的耗时操作
        Thread.sleep(100);
        log.info("{}", threadNum);
        Thread.sleep(100);
    }
}
复制代码

上面的代码中,我们定义了请求的数量为200,当这200个请求被处理完成之后,才会执行System.out.println("finish");.

//可以设置等待时间,It will be executed after this time,Does not wait until the counter becomes0,But the previously given thread will still be executed
countDownLatch.await(20, TimeUnit.MILLISECONDS);
复制代码

The rest of the above code is the same as the first code,使用了waitSet to wait for a certain amount of time before continuing to execute the method.

/** * CountDownLatch Simulate calling multiple tasks concurrently * * @author zjq */
@Slf4j
public class CountDownLatchExample3 {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(2) {
            @Override
            public void await() throws InterruptedException {
                super.await();
                log.info("What the main thread executes after other threads have finished executing");
                log.info("threadName:{},", Thread.currentThread().getName() + " count down is ok");
            }
        };

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    log.info(Thread.currentThread().getName() + "任务已完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //计数器减1
                    countDownLatch.countDown();
                }
            }
        }, "thread111");

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    log.info(Thread.currentThread().getName() + "任务已完成");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //计数器减1
                    countDownLatch.countDown();
                }
            }
        }, "thread222");


        thread1.start();
        thread2.start();

        countDownLatch.await();
        log.info("====everything is end====");
    }

}
复制代码

The above code executes the output result:

[thread111] INFO com.zjq.concurrency.aqs.CountDownLatchExample3 - thread111任务已完成
[thread222] INFO com.zjq.concurrency.aqs.CountDownLatchExample3 - thread222任务已完成
[main] INFO com.zjq.concurrency.aqs.CountDownLatchExample3 - What the main thread executes after other threads have finished executing
[main] INFO com.zjq.concurrency.aqs.CountDownLatchExample3 - threadName:main count down is ok,
[main] INFO com.zjq.concurrency.aqs.CountDownLatchExample3 - ====everything is end====
复制代码
/** * CountDownLatch After simulating the concurrent execution of multiple tasks, wait for the main thread to issue commands and perform subsequent operations at the same time * * @author zjq */
@Slf4j
public class CountDownLatchExample4 {

    public static void main(String[] args) throws InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    //All threads are blocked here,Waiting for the main thread command
                    log.info(Thread.currentThread().getName() + "已准备完毕!!");
                    countDownLatch.await();
                    log.info("【" + Thread.currentThread().getName() + "】" + "开始执行……");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
        // The main thread is ready to issue commands
        Thread.sleep(2000);
        log.info(Thread.currentThread().getName() + "发号施令,给我冲!!");
        // 主线程:执行发令
        countDownLatch.countDown();
    }

}
复制代码

Achieve maximum parallelism output results:

[Thread-3] INFO com.zjq.aqs.CountDownLatchExample4 - Thread-3已准备完毕!!
[Thread-0] INFO com.zjq.aqs.CountDownLatchExample4 - Thread-0已准备完毕!!
[Thread-2] INFO com.zjq.aqs.CountDownLatchExample4 - Thread-2已准备完毕!!
[Thread-1] INFO com.zjq.aqs.CountDownLatchExample4 - Thread-1已准备完毕!!
[Thread-4] INFO com.zjq.aqs.CountDownLatchExample4 - Thread-4已准备完毕!!
[main] INFO com.zjq.aqs.CountDownLatchExample4 - main发号施令,给我冲!!
[Thread-3] INFO com.zjq.aqs.CountDownLatchExample4 - 【Thread-3】开始执行……
[Thread-1] INFO com.zjq.aqs.CountDownLatchExample4 - 【Thread-1】开始执行……
[Thread-0] INFO com.zjq.aqs.CountDownLatchExample4 - 【Thread-0】开始执行……
[Thread-2] INFO com.zjq.aqs.CountDownLatchExample4 - 【Thread-2】开始执行……
[Thread-4] INFO com.zjq.aqs.CountDownLatchExample4 - 【Thread-4】开始执行……
复制代码

CountDownLatch 的不足

CountDownLatch是一次性的,计数器的值只能在构造方法中初始化一次,之后没有任何机制再次对其设置值,当CountDownLatch使用完毕后,它不能再次被使用.

CountDownLatch应用场景

(1)实现最大的并行性:有时我们想同时启动多个线程,实现最大程度的并行性.例 如,我们想测试一个单例类.如果我们创建一个初始计数为1的CountDownLatch,并 Make all threads wait on this lock,那么我们可以很轻松地完成测试.我们只需调用 一次 countDown()方法就可以让所有的等待线程同时恢复执行. (2)开始执行前等待n个线程完成各自任务:For example, the application startup class ensures that the user is being processed 请求前,所有N个外部系统已经启动和运行了. (3)死锁检测:一个非常方便的使用场景是,你可以使用n个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁.

本文内容到此结束了,

如有收获欢迎点赞收藏关注️,您的鼓励是我最大的动力.

如有错误疑问欢迎各位大佬指出.

主页共饮一杯无的博客汇总

保持热爱,奔赴下一场山海.

a37032f76d3ebe77e3e3d265ff1e1d7.jpg

copyright notice
author[share a drink],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/218/202208061824286072.html

Random recommended