1. ReentrantLock 源代码
使用AQS框架,CAS的操作代替了Synchronized里面的重量级锁, AQS里边维护一个队列,存储需要拿到资源的Thread
a. ReentrantLock 内部类
abstract static class Sync extends AbstractQueuedSynchronizer
nonfairTryAcquire
tryRelease
static final class NonfairSync extends Sync
static final class FairSync extends Sync
b. 构造方法
public ReentrantLock() {
sync = new NonfairSync();
}
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
c. 重点方法
public void lock() {
sync.lock();
}
public void unlock() {
sync.release(1);
}
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
2. class AbstractQueuedSynchronizer
a. 内部类
static final class Node
public class ConditionObject
b. 变量
private transient volatile Node head;
private transient volatile Node tail;
private volatile int state;
c. 主要方法
使用For去不断的循环查看前面的Node是Head,如果是,则试着获取锁,直到获取完锁才停止