ReentrantLock是什么该怎么理解?

ReentrantLock是可重入的独占锁,所以在同一时刻只有一个线程可以获取到该锁,其他想要获取该锁的线程会被阻塞,放入到该锁的AQS阻塞队列。类图如下

ReentrantLock是什么该怎么理解?_第1张图片

分析ReentrantLock源码,右下图源码可以看出ReentrantLock底层还是由AQS实现的。

ReentrantLock是什么该怎么理解?_第2张图片

分析ReentrantLock的源码构造函数可知,ReentrantLock有两个分别实现非公平(NonfairSync)及公平(FairSync)策略的子类,还可以看出ReentrantLock默认采用非公平锁。
/**
 * Creates an instance of {@code ReentrantLock}.
 * This is equivalent to using {@code ReentrantLock(false)}.
 */
public ReentrantLock() {
    sync = new NonfairSync();
}

/**
 * Creates an instance of {@code ReentrantLock} with the
 * given fairness policy.
 *
 * @param fair {@code true} if this lock should use a fair ordering policy
 */
public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
}

下面来分析AQS(AbstractQueuedSynchronized)的state的变量的意义。

ReentrantLock是什么该怎么理解?_第3张图片

其中state用volatile来修饰,则说明state在多线程中是可见的。

state在不同的锁中所具有的意义不一样,在ReentrantLock中state含义:因为ReentrantLock是可重入独占锁,及在线程尝试第一次获取到锁的时候state状态置为1,如果CAS成功则说明当前线程获取到了该锁,然后会记录该锁的持有者为此线程。如果此线程已经持有锁第二次获取锁的时候则state置为2。及state记录的是线程可重入获取锁的次数。如果当前线程释放锁那么state值减1,直到减为0的时候则当前线程释放该锁。

下面来分析ReentrantLock的lock方法如下:

/**
 * Acquires the lock.
 *
 * 

Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * *

If the current thread already holds the lock then the hold * count is incremented by one and the method returns immediately. * *

If the lock is held by another thread then the * current thread becomes disabled for thread scheduling * purposes and lies dormant until the lock has been acquired, * at which time the lock hold count is set to one. */ public void lock() { sync.lock(); }

在ReentrantLock中的源码注释已经说的很明白了翻译一下就是:

当前线程尝试获取锁的时候,如果当前锁没有被其他线程获取,那么设置当前锁的持有者为此线程并设置AQS的状态为1,直接返回。如果当前线程已经获取到锁那么就设置AQS状态值加1返回。如果当前锁已经被其他线程持有,那么调取当前lock()方法的线程会被阻塞到此锁的AQS阻塞队列中。

 

 

你可能感兴趣的:(ReentrantLock是什么该怎么理解?)