码迷,mamicode.com
首页 > 其他好文 > 详细

ReentrantLock三大特性

时间:2020-05-06 12:05:36      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:dia   row   air   throw   queue   ted   src   next   内部类   

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三大特性

标签:dia   row   air   throw   queue   ted   src   next   内部类   

原文地址:https://www.cnblogs.com/lt123/p/12835322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!