ReentrantLock原码学习:一、非公平锁

ReentrantLock

ReentrantLock分为公平锁和非公平锁,从有参构造器中可以看出,公平锁对象创建是内部类:new NonfairSync()

    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

NonfairSync的源码如下所示,先分析lock()方法,从该方法可以看出,所谓的上锁过程,就是将AQS中的变量status设置为1,并将当前线程设置

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

        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

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

你可能感兴趣的:(java)