ReentrantLock

2020-03-04  本文已影响0人  李逍遥JK

源码解析

    /**
     * 尝试获取锁
     */
    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;
    }
上一篇下一篇

猜你喜欢

热点阅读