JDK源码-ReetrantReadWriteLock(可重入读写锁)

11 篇文章 0 订阅
  • 读锁加锁:没有线程持有锁,或者持有的都是读锁
  • 写锁加锁:没有线程持有锁

写锁

加锁

public void lock() {
    sync.acquire(1);
}

public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

protected final boolean tryAcquire(int acquires) {
    Thread current = Thread.currentThread();
    int c = getState();
    int w = exclusiveCount(c); //AQS状态中独占锁的数目
    if (c != 0) { //有线程持有锁
        //(1)没有独占锁全是共享锁时,加锁失败
        //(2)存在独占锁且不是当前线程持有时,加锁失败
        if (w == 0 || current != getExclusiveOwnerThread())
            return false;
        //独占锁阈值限制
        if (w + exclusiveCount(acquires) > MAX_COUNT)
            throw new Error("Maximum lock count exceeded");
        // Reentrant acquire
        setState(c + acquires);
        return true;
    }
    //阻塞场景,比如公平锁场景当前线程在AQS队列中有前驱节点
    if (writerShouldBlock() ||
        !compareAndSetState(c, c + acquires))
        return false;
    //可重入锁状态设置
    setExclusiveOwnerThread(current);
    return true;
}

解锁

public final boolean release(int arg) {
    if (tryRelease(arg)) {
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h); //唤醒节点
        return true;
    }
    return false;
}

protected final boolean tryRelease(int releases) {
    if (!isHeldExclusively()) //没有线程持有锁,抛错
        throw new IllegalMonitorStateException();
    int nextc = getState() - releases; //状态扣减
    boolean free = exclusiveCount(nextc) == 0;
    if (free) //状态归零,已经没有线程持有锁
        setExclusiveOwnerThread(null);
    setState(nextc);
    return free;
}

读锁

加锁

同写锁的加锁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值