美文网首页
ReentrantLock

ReentrantLock

作者: 李逍遥JK | 来源:发表于2020-03-04 21:42 被阅读0次

源码解析

    /**
     * 尝试获取锁
     */
    protected final boolean tryAcquire(int acquires) {
        // 获取当前线程
        final Thread current = Thread.currentThread();
        // 获取锁的状态
        int c = getState();
        // 没有加锁
        if (c == 0) {
            /*
             * 先判断是否需要排队,如果不需要,才获取锁改变state
             * 如果需要,则要进行排队
             */
            if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                setExclusiveOwnerThread(current);
                return true;
            }
        }
        // 如果当前线程已经获取锁了 state+acquires 所以当state > 1 时为重入锁
        else if (current == getExclusiveOwnerThread()) {
            int nextc = c + acquires;
            // nextc < 0 的情况这种情况一般不会发生
            if (nextc < 0)
                throw new Error("Maximum lock count exceeded");
            setState(nextc);
            return true;
        }
        // 返回获取锁失败
        return false;
    }

相关文章

网友评论

      本文标题:ReentrantLock

      本文链接:https://www.haomeiwen.com/subject/qdifqhtx.html