关于java:JDK8-new-ReentrantLock加锁流程二

6次阅读

共计 624 个字符,预计需要花费 2 分钟才能阅读完成。

new ReentrantLock(true); 加锁流程:

protected final boolean tryAcquire(int acquires) {
    // 获取以后线程
    final Thread current = Thread.currentThread();
    // 获取 state 值
    int c = getState();
    // 还没有线程占用
    if (c == 0) {//!( 头节点和尾节点不是一个节点 &&(头节点的 next -> NULL 或者 头节点.next 节点 不是 以后线程))
        // 也就是说,头尾是一个节点 或者 头节点.next 节点的线程是以后线程
        if (!hasQueuedPredecessors() &&
            //cas 0 -> 1
            compareAndSetState(0, acquires)) {
            / 设置独占线程
            setExclusiveOwnerThread(current);
            return true;
        }
    }
    // 以后线程等于独占线程
    else if (current == getExclusiveOwnerThread()) {
        //state 值 +1
        int nextc = c + acquires;
        if (nextc < 0)
            throw new Error("Maximum lock count exceeded");
        // 从新赋值 state 值
        setState(nextc);
        return true;
    }
    // 否则返回 false
    return false;
}

如果取得锁失败,和 JDK8 new ReentrantLock() 加锁流程(一)中流程一样!

正文完
 0