ReentrantLock

ReentrantLock

  • ReentrantLock的原理
    • 使用
    • lock方法
      • 1.tryAcquire(arg)
  • 写着写着发现内容还挺多的,累了,不写了,有空再继续完善。

ReentrantLock的原理

使用

使用的话很简单,只要new个对象出来,然后调用lock()方法就可以加锁,调用unlock()方法进行解锁。
这里有个公平锁和非公平锁的区别,后面解释,我这里以公平锁为例。

 	//public ReentrantLock() {
   //     sync = new NonfairSync();
    //}

    //public ReentrantLock(boolean fair) {
    //    sync = fair ? new FairSync() : new NonfairSync();
    //}
    //如上: 构造方法传入true这个参数,new出来的对象是公平锁,默认false
    ReentrantLock reentrantLock = new ReentrantLock(true);

    reentrantLock.lock();
	// 业务代码。。。。
	reentrantLock.unlock();

lock方法

点进去看到源码是这样的:

    public void lock() {
        sync.lock();
    }

然后Ctrl + Atl + B继续点进去看,我们看第一个公平锁的实现
ReentrantLock_第1张图片
然后查一下字典发现acquire是获得、取得的意思。然后他传了个 1 到 这个acquire方法里面

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

然后继续看acquire方法

    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

这里有几行代码,我门可以分成多个部分去看:

1.tryAcquire(arg)
2.addWaiter(Node.EXCLUSIVE)
3.acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
4.selfInterrupt()

1.tryAcquire(arg)

这个tryAcquire方法,从字面意思就可以知道这是线程尝试去获取锁。具体实现代码如下:

        /**
         * 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(); // 锁状态,加锁成功则为1,重入+1 解锁则为0     																																																																												            																																																																												             		  
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;
        }

写着写着发现内容还挺多的,累了,不写了,有空再继续完善。

你可能感兴趣的:(ReentrantLock)