并发编程 —— CountDownLatch 讲解

CountDownLatch 介绍

CountDownLatch 是用于等待线程的执行,等待线程数量为 0 后,则结束等待,执行该线程等待后所要执行的代码。

例子如下:

private static CountDownLatch caDownLatch = new CountDownLatch(2);

public static void main(String[] args) {
	new Thread(){
		public void run() {
			System.out.println("线程" + Thread.currentThread().getName() + "开始");
			System.out.println("线程" + Thread.currentThread().getName() + "等待其它两个线程执行结束");
			try {
				caDownLatch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("其它两个线程执行结束");
			System.out.println("线程" + Thread.currentThread().getName() + "结束");
		};
	}.start();
	new Thread(){
		public void run() {
			System.out.println("线程" + Thread.currentThread().getName() + "执行");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			caDownLatch.countDown();
		};
	}.start();
	new Thread(){
		public void run() {
			System.out.println("线程" + Thread.currentThread().getName() + "执行");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			caDownLatch.countDown();
		};
	}.start();
}

执行结果为:

线程Thread-0开始
线程Thread-0等待其它两个线程执行结束
线程Thread-1执行
线程Thread-2执行
其它两个线程执行结束
线程Thread-0结束

CountDownLatch 源码分析

CountDownLatch 内部通过标记和阻塞线程和唤醒线程来实现功能。

首先分析 await() 方法:

public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
        throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (tryAcquireShared(arg) < 0) // 如果指定等待的数量不等于 0
        doAcquireSharedInterruptibly(arg);
}


private void doAcquireSharedInterruptibly(int arg)
    throws InterruptedException {
    // 插入该线程节点
    final Node node = addWaiter(Node.SHARED);
    boolean failed = true;
    try {
        for (;;) {
            // ...
            // parkAndCheckInterrupt 用于阻塞线程并判断是否被中断,内部调用 LockSupport.park 来实现
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                throw new InterruptedException();
        }
    } finally {
        if (failed) // 如果失败,就恢复
            cancelAcquire(node);
    }
}

接下来看 countDown() 方法:

public void countDown() {
    sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
    // tryReleaseShared 对标记减一,已经没有等待的线程时返回 true
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

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
                // 唤醒阻塞的线程,继续执行,通过 LockSupport.unpark
                unparkSuccessor(h);
            }
            // ...
        }
        // ...
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值