ReentrantLock三大特性

Posted lt123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReentrantLock三大特性相关的知识,希望对你有一定的参考价值。

Doug lea

可重入 同一线程某方法获取该锁后,如果再另一方法尝试再获取锁,不会被阻塞。 关键字:同一线程 不同方法 阻塞 

公平

非公平

 

Sync接口的不同静态内部类实现   实现了两方法 tryAcquire lock 设计模式中的模板模式

FairSync

NonFairSync

 

    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

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

        /**
         * Fair version of tryAcquire.  Don‘t grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
                if (!hasQueuedPredecessors() &&
                    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);
                return true;
            }
            return false;
        }
    }

 

    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }

 技术图片

以上是关于ReentrantLock三大特性的主要内容,如果未能解决你的问题,请参考以下文章

Java中面向对象的三大特性之封装

synchronizedLock接口Condition接口读写锁及ReentrantLock(重入锁) 特性及使用

面向对象三大特性

三大特性:封装,继承,多态

面向对象 三大特性 五大原则

理解java的三大特性之继承