并发-CountDownLatch

前言

   最近小咸儿在看项目代码时发现有用到CountDownLatch,那这个到底是什么回事呢?又用来干什么呢?让小咸儿来一探究竟。


问题

   1、CountDownLatch是什么?
   2、CountDownLatch有什么特性?
   3、CountDownLatch适用于什么场景?
   4、CountDownLatch的初始次数是否可以调整?
   5、CountDownLatch底层是运行什么实现的?

简介

CountDownLatch是什么?

   CountDownLatch是一个计数器闭锁,通过它可以完成类似阻塞当前线程的功能,即:一个线程或多个线程一直等待,直到其他线程执行的操作完成。
在这里插入图片描述

类结构:Sync为CountDownLatch的内部类

在这里插入图片描述

特性

构造函数

/**
 * Constructs a {@code CountDownLatch} initialized with the given count.
 *
 * @param count the number of times {@link #countDown} must be invoked
 *        before threads can pass through {@link #await}
 * @throws IllegalArgumentException if {@code count} is negative
 */
 public CountDownLatch(int count) {
   
     if (count < 0) throw new IllegalArgumentException("count < 0");
     this.sync = new Sync(count);
 }

// Sync内部类方法,传入初始次数
   Sync(int count) {
   
      setState(count);
   }

  通过构造器初始化计数器的值,可实际上是把计数器的值赋值给了AQS的state,也就是用AQS的状态值来表示计数器值。

  接下来看一下CountDownLatch中几个重要方法内部是如何调用AQS来实现功能的。

void await()方法

  当前线程调用了CountDownLatch对象的await()方法后,当前线程会被阻塞,直到下面情况之一才会返回:

  • 当所有的线程都调用了CountDownLatch对象的countDown()方法后,也就是计数器为0的时候。
  • 其他线程调用了当前线程的interrupt()方法中断了当前线程,当前线程会抛出InterruptedException
    异常后返回。

  接下来看一下await()方法内部具体是如何实现的?

// CountDownLatch的await()方法
public void await() throws InterruptedException {
   
	   // 调用AQS的acquireSharedInterruptibly()方法
       sync.acquireSharedInterruptibly(1);
}

  实际上调用的是AQS的acquireSharedInterruptibly()方法

/**
 * Acquires in shared mode, aborting if interrupted.  Implemented
 * by first checking interrupt status, then invoking at least once
 * {@link #tryAcquireShared}, returning on success.  Otherwise the
 * thread is queued, possibly repeatedly blocking and unblocking,
 * invoking {@link #tryAcquireShared} until success or the thread
 * is interrupted.
 * @param arg the acquire argument.
 * This value is conveyed to {@link #tryAcquireShared} but is
 * otherwise uninterpreted and can represent anything
 * you like.
 * @throws InterruptedException if the current thread is interrupted
 */
 public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
   
	 // 如果线程被中断则抛异常
    if (Thread.interrupted())
        throw new InterruptedException();
       // 尝试看当前是否计数值为0,为0则返回,否则进入AQS的队列等待
       
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,您想了解关于Java并发编程中的CountDownLatch吗? CountDownLatch是Java并发编程中非常重要的一个工具类,它可以让某个线程等待其他线程完成后再继续执行。它的作用类似于倒计时门闩,当count值减为0时,所有等待者都会被唤醒。 CountDownLatch是一次性的,也就是说,它的计数器只能使用一次。如果需要重复使用,可以考虑使用CyclicBarrier。 在使用CountDownLatch时,我们需要先创建一个CountDownLatch对象,并指定计数器的初始值。然后在需要等待的线程中调用await()方法进行等待,同时在其他线程中调用countDown()方法进行计数器的减1操作。 举个例子,假设我们有一个需求:主线程需要等待两个子线程完成后再执行。那么可以这样编写代码: ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程1").start(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "执行开始"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "执行完毕"); countDownLatch.countDown(); }, "线程2").start(); System.out.println(Thread.currentThread().getName() + "等待子线程执行完毕"); countDownLatch.await(); System.out.println(Thread.currentThread().getName() + "所有子线程执行完毕,继续执行主线程"); } } ``` 在上面的例子中,我们首先创建了一个计数器初始值为2的CountDownLatch对象,然后创建了两个线程分别进行一些操作,并在操作结束后调用countDown()方法进行计数器减1操作。在主线程中,我们调用await()方法进行等待,直到计数器减为0时,主线程才会继续执行。 希望能够对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值