ReentrantLock和同步器AbstractQueuedSynchronizer
1、可重入锁,加锁
ReentrantLock lock = new ReentrantLock();
lock.lock();
2、我们来看lock()的方法;Sync是ReentrantLock 的一个抽象静态内部类,它实现了同步器AbstractQueuedSynchronizer
public void lock() {
sync.lock();
}
3、ReentrantLock 重写了Sync的抽象方法lock(),ReentrantLock实现用两种方式实现lock()方法,
默认是非公平锁,下面我们来看非公平锁的实现(独占式获取锁)
final void lock() {
//cas方式尝试修改锁的状态值,0是期待值,1是修改值,
//如果期待值和当前的内存值是相同的,则修改内存值为1,修改成功,则当前线程获取锁成功
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
//如果当前的内存值不是0,当前对象上有锁,尝试获取锁
acquire(1);
}
4、尝试获取锁,acquire()方法,非公平锁
public final void acquire(int arg) {
//tryAcquire()非公平锁获取锁,如果获取锁失败,则把当前线程加入到同步队列中
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//如果没有获取到锁,当前线程中断
selfInterrupt();
}
//非公平锁实现的tryAcquire方法如下:获取锁
final boolean nonfairTryAcquire(int acquires) {
//获取当前线程的执行对象
final Thread current = Thread.currentThread();
//获取当前锁的状态
int c = getState();
//进入条件:c==0当前对象没有锁
if (c == 0) {
//进入条件:通过cas方式获取锁成功
if (compareAndSetState(0, acquires)) {
//设置当前线程为执行线程
setExclusiveOwnerThread(current);
return true;
}
}
//进入条件:如果当前对象有锁,并且拥有锁的线程是当前线程
else if (current == getExclusiveOwnerThread()) {
//当前锁的状态值+1
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
5、如果获取锁失败,把当前节点设置为同步队列的尾节点(addWaiter);染后执行到acquireQueued()方法,该方法就是让该节点一直自旋,直到节点成功获取锁,退出自旋。
我们看addWaiter()方法和acquireQueued的源码:
private Node addWaiter(Node mode) {
//创建node节点
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail;
//如果尾节点不为null
if (pred != null) {
//把尾结点和前驱节点关联起来
node.prev = pred;
//cas设置当前节点为尾节点
if (compareAndSetTail(pred, node)) {
//尾节点设置成功,把尾节点和原尾节点的后驱关联起来
pred.next = node;
return node;
}
}
enq(node);
return node;
}
final boolean acquireQueued(final Node node, int arg) {
//
boolean failed = true;
try {
boolean interrupted = false;
//自旋,当node的前节点p是头节点,并且获取到锁,才退出自旋
for (;;) {
//获取当前节点的前驱节点
final Node p = node.predecessor();
//进入条件:node的前区节点p是头节点,并且获取到锁
if (p == head && tryAcquire(arg)) {
//获取锁成功,设置为头节点
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}