ReentrantLock基于AQS,它实现了公平锁和非公平锁,在开发中可以用它对共享资源进行同步,此外,和synchronized一样,ReentrantLock支持可重入锁,但ReentrantLock在调度上更灵活。
首先来看ReentrantLock的继承关系,ReentrantLock实现了Lock接口。在面向对象的概念中,既然ReentrantLock是Lock的一种具体实现,呢么它必然拥有Lock的抽象意义。
Lock只是定义了一些方法的语义,规定了它的 实现类需要满足这些语义。
关于ReentrantLock类的源码,我们关注一下三个方面:
- 属性:sync
- 内部类:Sync,NofairSync,FairSync
- 方法:
继承/实现方法:实现Lock的方法
私有方法
属性
ReentrantLock只有一个属性:Sync类型的变量sync。sync被final修饰,意味着一旦初始化,就不可修改引用了。那么它的初始化时机是什么时候?
private final Sync sync;
在ReentrantLock构造器中:
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
默认非公平锁。
内部类
Sync
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();
/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
*/
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;