CountDownLatch源码解析

14 篇文章 0 订阅
14 篇文章 0 订阅

CountDownLatch源码解析

countDownLatch是一个用来实现同步的工具,允许一个或者多个线程等待其他的线程完成一系列的操作。

类定义

public class CountDownLatch{}

属性定义

private final Sync sync;

Sync是一个内部类,一个同步器。

内部类Sync的定义

private static final class Sync extends AbstractQueuedSynchronizer{
    private static final long serialVersionUID = 4982264981922014374L;
    
    Sync(int count){
        setState(count);
    }
    
    int getCount(){
        getState();
    }
    
    protected int tryAcquireShared(int acquires){
        return (getState() == 0) ? 1 : -1;
    }
    
    protected boolean tryReleaseShared(int releases){
        // 减少count的值,当count的值变成0时,返回
        for(;;){
            int c = getState();
            if(c == 0)
                return false;
            int nextc = c - 1;
            if(compareAndSetState(c, nextc))
                return nextc == 0;
        }
    }
}

Sync是AbstractQueuedSynchronizer的子类。CountDownLatch的同步控制器,使用AQS的state来代表count。

构造函数

public CountDownLatch(int count){
    if(count < 0) throw new IllegalArgumentException("count < 0");
    this.sync = new Sync(count);
}

使用给定的count创建一个CountDownLatch对象。

方法

// 会导致当前线程进入等待状态,直到count的值变成0,或者被中断
public void await() throws InterruptedException{
    sync.acquireSharedInterruptibly(1);
}

// 与await相同,只不过增加了超时的功能
public boolean await(long timeout, TimeUnit unit) throws InterruptedException{
    return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}

// 使count的值减一,如果count的值变成0,会唤醒所有等待的线程.
public void countDown(){
    sync.releaseShared(1);
}

// 获取count的值
public long getCount(){
    return sync.getCount();
}

public String toString(){
    return super.toString() + "[Count = " + sync.getCount() + "]";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值