Java-J.U.C之并发工具类CountDownLatch-XXOO

一、CountDownLatch是什么?

CountDownLatch是通过一个计数器来实现的,当我们在new 一个CountDownLatch对象的时候需要带入该计数器值,该值就表示了线程的数量。每当一个线程完成自己的任务后,计数器的值就会减1。当计数器的值变为0时,就表示所有的线程均已经完成了任务,然后就可以恢复等待的线程继续执行。

在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

CountDownlatch与CyclicBarrier的区别:

1.CountDownLatch的作用是允许1或N个线程等待其他线程完成执行; 而CyclicBarrier则是允许N个线程相互等待

2.CountDownLatch的计数器无法被重置;CyclicBarrier的计数器可以被重置后使用,因此它被称为是循环的barrier。

二、代码示例

1.飞机示例

private static CountDownLatchT1 countDownLatch = new CountDownLatchT1(5);

    /**
     * Plan线程,等待乘客到达起飞
     */
    static class PlanThread extends Thread{
        @Override
        public void run() {
            log.info("飞机在等待,总共有" + countDownLatch.getCount() + "个乘客乘坐飞机...");
            try {
                // 飞机等待
                //countDownLatch.await();
                countDownLatch.await(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            log.info("所有乘客都已经到齐了,起飞吧...");
        }
    }

    /**
     * 乘客上飞机
     */
    static class PeopleThread  extends Thread{
        @Override
        public void run() {
            log.info(Thread.currentThread().getName() + "乘客,到达飞机....");
            // 乘客到达飞机 count - 1
            countDownLatch.countDown();
        }
    }

    public static void main(String[] args) {
        // 飞机线程启动
        new PlanThread().start();

        for(long i = 0,j = countDownLatch.getCount() ; i < j ; i++){
            new PeopleThread().start();
        }
    }


2.源码分析

package com.yl.springboottest.consurrency.countdownlatch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 描述:J.U.C之并发工具类:CountDownLatch
 *
 * @author: yanglin
 * @Date: 2020-11-27-10:19
 * @Version: 1.0
 */
@Slf4j
public class CountDownLatchT1 {
    

    /**
     * Synchronization control For 
     * Uses AQS state to represent count.
     * Sync继承AQS
     *
     * 同步控制使用AQS状态表示计数。
     */
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;

        Sync(int count) {
            setState(count);
        }

        // 获取同步状态
        int getCount() {
            return getState();
        }

        // 获取同步状态
        @Override
        protected int tryAcquireShared(int acquires) {
            // getState()获取同步状态,其值等于计数器的值,从这里我们可以看到如果计数器值不等于0,
            // 则会调用doAcquireSharedInterruptibly(int arg),该方法为一个自旋方法会尝试
            // 一直去获取同步状态
            return (getState() == 0) ? 1 : -1;
        }

        // 释放同步状态
        // tryReleaseShared(int arg)方法被CountDownLatch的内部类Sync重写:
        @Override
        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero 减量计数;转换为零时发出信号
            for (;;) {
                // 获取锁状态
                int c = getState();
                // c == 0 直接返回,释放锁成功
                if (c == 0)
                    return false;
                // 计算新“锁计数器”
                int nextc = c-1;
                // 更新锁状态(计数器)
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

    private final Sync sync;

    /**
     * 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
     *
     * 构造一个用给定计数初始化的 CountDownLatch
     */
    public CountDownLatchT1(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.
     *
     * <p>If the current count is zero then this method returns immediately.
     *
     * <p>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:
     * <ul>
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread.
     * </ul>
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     *
     *         使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断
     */
    public void await() throws InterruptedException {
        // await其内部使用AQS的acquireSharedInterruptibly(int arg):
        sync.acquireSharedInterruptibly(1);
    }

    /**
     * Causes the current thread to wait until the latch has counted down to
     * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
     * or the specified waiting time elapses.
     *
     * 使当前线程等待,直到闩锁计数到零,除非线程是{@linkplainthread #interrupt interrupted},
     * 或指定的等待时间已过。
     *
     * <p>If the current count is zero then this method returns immediately
     * with the value {@code true}.
     *
     * <p>If the current count is greater than zero then the current
     * thread becomes disabled for thread scheduling purposes and lies
     * dormant until one of three things happen:
     * <ul>
     * <li>The count reaches zero due to invocations of the
     * {@link #countDown} method; or
     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
     * the current thread; or
     * <li>The specified waiting time elapses.
     * </ul>
     *
     * <p>If the count reaches zero then the method returns with the
     * value {@code true}.
     *
     * <p>If the current thread:
     * <ul>
     * <li>has its interrupted status set on entry to this method; or
     * <li>is {@linkplain Thread#interrupt interrupted} while waiting,
     * </ul>
     * then {@link InterruptedException} is thrown and the current thread's
     * interrupted status is cleared.
     *
     * <p>If the specified waiting time elapses then the value {@code false}
     * is returned.  If the time is less than or equal to zero, the method
     * will not wait at all.
     *
     * 如果指定的等待时间已经过去,则值{@code false} 返回。如果时间小于或等于零,方法根本不会等。
     *
     * @param timeout the maximum time to wait 等待的最长时间
     * @param unit the time unit of the {@code timeout} argument
     * @return {@code true} if the count reached zero and {@code false}
     *         if the waiting time elapsed before the count reached zero
     * @throws InterruptedException if the current thread is interrupted
     *         while waiting
     */
    public boolean await(long timeout, TimeUnit unit)
            throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    /**
     * Decrements the count of the latch, releasing all waiting threads if
     * the count reaches zero.
     *
     * <p>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.
     *
     * <p>If the current count equals zero then nothing happens.
     *
     * 递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
     */
    public void countDown() {
        // 内部调用AQS的releaseShared(int arg)方法来释放共享锁同步状态
        sync.releaseShared(1);
    }

    /**
     * Returns the current count.
     *
     * <p>This method is typically used for debugging and testing purposes.
     *
     * @return the current count
     *
     * 返回当前计数。
     */
    public long getCount() {
        return sync.getCount();
    }

    /**
     * Returns a string identifying this latch, as well as its state.
     * The state, in brackets, includes the String {@code "Count ="}
     * followed by the current count.
     *
     * @return a string identifying this latch, as well as its state
     */
    @Override
    public String toString() {
        return super.toString() + "[Count = " + sync.getCount() + "]";
    }
}

 


总结

CountDownLatch内部通过共享锁实现。在创建CountDownLatch实例时,需要传递一个int型的参数:count,该参数为计数器的初始值,也可以理解为该共享锁可以获取的总次数。当某个线程调用await() 方法,程序首先判断count的值是否为0,如果不会0的话则会一直等待直到为0为止。当其他线程调用 countDown()方法时,则执行释放共享锁状态,使count值 - 1。当在创建CountDownLatch时初始化的count参数,必须要有count线程调用countDown方法才会使计数器count等于0,锁才会释放,前面等待的线程才会继续运行。注意CountDownLatch不能回滚重置。

おすすめ

転載: blog.csdn.net/qq_35731570/article/details/110229023