ReentrantLock的Syn内部类分析

    final boolean nonfairTryAcquire(int acquires) {

            final Thread current = Thread.currentThread();    // 获得当前线程
            int c = getState();    // 获取锁的状态值
            if (c == 0) {    // 如果锁未被占用,则获得该锁
                if (compareAndSetState(0, acquires)) {    // cas机制,多线程抢占锁,谁RP好,谁获得锁
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 如果线程已获得当前锁
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow    // 状态溢出异常
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);    // 状态值增加
                return true;
            }
            return false;
        }

方法尝试为当前线取排它的获取非公平锁,如果当前线程未获得锁,则对线程进行锁定,如果线程已获得锁,则状态值+1,如果锁被占用,则返回false。

protected final boolean tryRelease(int releases) {
            int c = getState() - releases;    // 减去释放值后的状态值
            if (Thread.currentThread() != getExclusiveOwnerThread())    // 判断时候在同一个线程
                throw new IllegalMonitorStateException();
            boolean free = false;
            if (c == 0) {    // 如果状态值为0,则释放锁
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);    // 如果状态值不为0,设置减去释放值后的状态值
            return free;
        }

尝试释放当前锁,如果状态值为0则释放锁,如果不为0返回false。

protected final boolean isHeldExclusively() {
            // While we must in general read state before owner,
            // we don't need to do so to check if current thread is owner
            // 判断当前线程是否拥有该锁
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

在排它模式下,状态是否被占用。

final ConditionObject newCondition() {
            return new ConditionObject();
        }

Lock中通过Condition实现wait和notify,该方法用于创建一个Condition。

 final Thread getOwner() {
            return getState() == 0 ? null : getExclusiveOwnerThread();
        }

返回控制锁的线程,如果存在线程。

 final int getHoldCount() {
            return isHeldExclusively() ? getState() : 0;
        }

如果线程占用了锁,则返回锁的状态值,否则返回0。

 final boolean isLocked() {
            return getState() != 0;
        }

判断锁是否被占用,返回boolean。

 private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
            s.defaultReadObject();
            setState(0); // reset to unlocked state
        }
方法从该流中读取当前类的非静态和非瞬态字段。这也许只能称为从类反序列化readObject方法。它会抛出NotActiveException如果它被调用。并重置状态值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值