JDK源码--ReetrantLock(可重入锁)

11 篇文章 0 订阅
  • 加锁时判断是否已加锁的为当前线程,如果是则加锁成功同时增加锁次数
  • 解锁时需要把加的锁次数扣减至0才算解锁成功
  • 分为公平和非公平锁

加锁

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

protected final boolean tryAcquire(int acquires) {
    final Thread current = Thread.currentThread();
    int c = getState();
    if (c == 0) { //没有线程持有锁
        if (!hasQueuedPredecessors() && //AQS队列该线程没有前驱节点
            compareAndSetState(0, acquires)) {
            setExclusiveOwnerThread(current); //设置当前线程持有搜
            return true;
        }
    }
    //持有锁的就是当前线程
    else if (current == getExclusiveOwnerThread()) {
        int nextc = c + acquires; //增加锁次数
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        setState(nextc); //更新AQS状态
        return true;
    }
    return false;
}

解锁

public void unlock() {
    sync.release(1);
}

public final boolean release(int arg) {
    if (tryRelease(arg)) { //解锁成功,即锁次数已归零
        Node h = head;
        if (h != null && h.waitStatus != 0)
            unparkSuccessor(h); //唤醒AQS队列的后继节点
        return true;
    }
    return false;
}

protected final boolean tryRelease(int releases) {
    int c = getState() - releases; //扣减锁次数
    if (Thread.currentThread() != getExclusiveOwnerThread())
        throw new IllegalMonitorStateException(); //持有锁不是当前线程,不符合可重入锁规则,抛异常
    boolean free = false;
    if (c == 0) { //锁次数已归零,释放锁持有的配置
        free = true;
        setExclusiveOwnerThread(null);
    }
    setState(c);
    return free;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值