CountDownLatch源码分析

本文详细介绍了Java并发工具类CountDownLatch的使用及其内部实现原理,通过源码分析了CountDownLatch如何协调多个线程的同步,并展示了在实际代码中的应用示例。重点讲解了CountDownLatch与AbstractQueuedSynchronizer(AQS)的关系,以及在AQS中如何进行共享锁的获取和释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例子

public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i=0; i<3; i++) {
            new Thread(() -> {
                System.out.println("线程: " + Thread.currentThread().getName() + "开始执行");
                countDownLatch.countDown();
                System.out.println("线程: " + Thread.currentThread().getName() + "执行结束");
            }).start();
        }
        System.out.println("hahaha");
        countDownLatch.await();
        System.out.println("shutdown");
    }

countDownLatch会将线程阻塞在await语句那里,直到count计数为0,然后往后执行

源码分析

public class CountDownLatch {

	//同步器
	private final Sync sync;

//构造方法 传入一个计数
	public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
	//同步器 静态内部类 继承aqs
	private static final class Sync extends AbstractQueuedSynchronizer {
		//传入计数,设置到aqs的state
        Sync(int count) {
            setState(count);
        }
		//获取计数
        int getCount() {
            return getState();
        }
		//获取共享锁
        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }
		//释放共享锁
        protected boolean tryReleaseShared(int releases) {
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c-1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }
//await方法,将线程阻塞
	public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }
	//将计数减一
	public void countDown() {
        sync.releaseShared(1);
    }
}

public abstract class AbstractQueuedSynchronizer
    extends AbstractOwnableSynchronizer
    implements java.io.Serializable {
	
	//共享锁中断
	public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
            throw new InterruptedException();
		//count计数不为0时   计数为0,await放开,执行await之后的逻辑
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
	
	private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
		//将一个共享锁节点放入aqs队列
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    //count计数为0时
					if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
				//count计数不为0时,挂起线程,和上一篇reentrentLock一样的方法
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
	
	private void setHeadAndPropagate(Node node, int propagate) {
        Node h = head; 
        setHead(node);
		//propagate > 0	当前计数为0
        if (propagate > 0 || h == null || h.waitStatus < 0 ||
            (h = head) == null || h.waitStatus < 0) {
            Node s = node.next;
            if (s == null || s.isShared())
                doReleaseShared();
        }
    }
	
	//
	public final boolean releaseShared(int arg) {
        //当前计数为0
		if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
	
	//释放 循环将aqs队列中的所有共享锁一次性全部释放,aqs队列中的共享锁都出来执行其逻辑
	private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值