【Java】--CountDownLatch的介绍及应用

    技术2022-07-10  147

    CountDownLatch简介

    CountDownLatch是java.util.concurrent包中的一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。它主要用来协调多个线程之间的同步,起到一个同步器的作用。总的来说,CountDownLatch让一个或多个线程在运行过程中的某个时间点能停下来等待其他的一些线程完成某些任务后再继续运行。

    使用场景

    在一些应用场合中,需要等待某个条件达到要求后才能做后面的事情;同时当线程都完成后也会触发事件,以便进行后面的操作。 这个时候就可以使用CountDownLatch。CountDownLatch最重要的方法是countDown()和await(),前者主要是倒数一次,后者是等待倒数到0,如果没有到达0,就只有阻塞等待了。

    方法说明

    构造函数

    构造一个使用给定计数初始化的CountDownLatch。

    /** * Constructs a CountDownLatch initialized with the given count. * * Parameters: * count - the number of times countDown() must be invoked before threads can pass through await() * * Throws: * IllegalArgumentException - if count is negative **/ public CountDownLatch(int count)

    countDown

    递减锁存器的计数,如果计数到达零,则释放所有等待的线程。 如果当前计数大于零,则将其递减。 如果新计数为零,则将重新启用所有等待线程以进行线程调度。 如果当前计数等于零,则不发生任何操作。

    /** * Decrements the count of the latch, releasing all waiting threads if the count reaches zero. * If the current count is greater than zero then it is decremented. * If the new count is zero then all waiting threads are re-enabled for thread scheduling purposes. * If the current count equals zero then nothing happens. **/ public void countDown()

    await

    使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。如果当前计数为零,则此方法立刻返回 true 值。 如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下三种情况之一前,该线程将一直处于休眠状态:

    由于调用 countDown()方法,计数到达零;或者其他某个线程中断当前线程;或者已超出指定的等待时间。

    如果计数到达零,则该方法返回 true 值。

    如果当前线程:

    在进入此方法时已经设置了该线程的中断状态;或者在等待时被中断,

    则抛出 InterruptedException,并且清除当前线程的已中断状态。

    如果超出了指定的等待时间,则返回值为 false。如果该时间小于等于零,则此方法根本不会等待。

    参数:

    timeout - 要等待的最长时间

    unit - timeout 参数的时间单位。

    返回:

    如果计数到达零,则返回 true;如果在计数到达零之前超过了等待时间,则返回 false

    抛出:

    InterruptedException - 如果当前线程在等待时被中断

    /* Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen: The count reaches zero due to invocations of the countDown() method; or Some other thread interrupts the current thread. If the current thread: has its interrupted status set on entry to this method; or is interrupted while waiting, then InterruptedException is thrown and the current thread's interrupted status is cleared. Throws: InterruptedException - if the current thread is interrupted while waiting */ public boolean await(long timeout, TimeUnit unit) throws InterruptedException

    应用案例

    小明锁门

    有5位同学在教室上自习,小明需要等所有同学离开教室后将教室门锁上。

    public class CountDownLatchDemo { public static void main(String[] args) { for (int i = 0; i < 5; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "上完自习,离开教室"); },String.valueOf(i) ).start(); } System.out.println(Thread.currentThread().getName() + "小明锁门了"); } }

    结果: 2位同学离开教室后,小明就锁门了。 使用CountDownLatch后:

    public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch count = new CountDownLatch(5); for (int i = 0; i < 5; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "上完自习,离开教室"); count.countDown(); },String.valueOf(i) ).start(); } count.await(); System.out.println(Thread.currentThread().getName() + "小明锁门了"); } }

    结果: 5位同学都离开教室后,小明才锁门。

    秦灭六国

    战国时期,秦灭六国,一统天下。

    public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch count = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "国,被灭!"); count.countDown(); },String.valueOf(i) ).start(); } count.await(); System.out.println("秦灭六国,一统天下!!"); } }

    运行结果: 如何将数字替换成 楚国、齐国、燕国、赵国、魏国、韩国 呢?

    使用枚举解决: 增加枚举类

    public enum CountryEnum { ONE(0, "齐国"), TWO(1, "楚国"), THREE(2, "燕国"), FOUR(3, "赵国"), FIVE(4, "韩国"), SIX(5, "魏国"); private int retCode; private String retMsg; CountryEnum(int retCode, String retMsg) { this.retCode = retCode; this.retMsg = retMsg; } public static String forEach_Country(int index) { CountryEnum[] country = CountryEnum.values(); for (CountryEnum anEnum : country) { if (index == anEnum.retCode) { return anEnum.retMsg; } } return null; } } public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch count = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + ",被灭!"); count.countDown(); },CountryEnum.forEach_Country(i) ).start(); } count.await(); System.out.println("秦灭六国,一统天下!!"); } }

    运行结果:

    Processed: 0.032, SQL: 9