赞
踩
写这篇文章是让自己对AQS和ReentrantLock加深理解,需要配合之前的文章一起学习。
AQS(AbstractQueuedSynchronizer)初学
假设有3个线程A、B、C都调用lock.lock()方法获取锁,ReentrantLock 默认的构造方法调用的是非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
final void lock() {
if (compareAndSetState(0, 1))// ①
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);//②
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);// ③
}
}
①:假设线程A获取到锁往下执行,当线程B调用lock()方法的时候调用①失败 执行方法②(此方法在父类AQS中)代码如下:
public final void acquire(int arg) {
if (!tryAcquire(arg) //④
&&acquireQueued(addWaiter(Node.EXCLUSIVE), arg))//⑤
selfInterrupt();}
tyAcquire():由自定义锁实现在这里实际就是方法③ 主要就是通过改变state的状态来获取锁,没有获取到锁的话就执行方法⑤中的addWaiter()
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {⑥
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);⑦
return node;
}
线程B执行到此此时tail还是null 所以执行方法⑦ 循环CAS直到成功返回
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize ⑧
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {//⑨
t.next = node;
return t;
}
}
}
}
此时tail是null 必须先进行队列的初始化设置队列的头结点:成功以后如下图所示
方法⑨成功以后如下图所示:
结束循环继续执行方法⑤中的acquireQueued()方法:
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
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);
}
}
执行方法⑩p节点为头节点再次进行获取锁的操作(因为此时获取A线程已经执行完毕或者A线程取消了),假设此时线程A还没有结束执行方法⑪
将head节点的waitStatus设置为SIGNAL(-1)返回true继续执行方法⑫将线程B挂起
假设线程C和线程B一样的流程此时的状态图如下:
此时线程A执行完毕调用了 unlock()方法(实际上是调用的AQS的release方法):
public final boolean release(int arg) {
if (tryRelease(arg)) {//⑬
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);//⑭
return true;
}
return false;
}
调用方法⑬通过改变state释放锁,继续执行方法⑭
private void unparkSuccessor(Node node) {
/*
* If status is negative (i.e., possibly needing signal) try
* to clear in anticipation of signalling. It is OK if this
* fails or if status is changed by waiting thread.
*/
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
/*
* Thread to unpark is held in successor, which is normally
* just the next node. But if cancelled or apparently null,
* traverse backwards from tail to find the actual
* non-cancelled successor.
*/
Node s = node.next;//⑮
if (s == null || s.waitStatus > 0) {
s = null;
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
LockSupport.unpark(s.thread);//唤醒线程
}
此时的Node是指向头节点的,通过s=node.next 将s结点执行线程B的结点将线程B唤醒,然后线程B继续执行acquireQueued()方法里面的方法⑩
进入方法⑩后将会重新设置头节点将原来的头节点删除将原来线程B所在的结点设置为头节点,如下图所示:
线程B执行完以后也会执行unlock()方法按上述的流程将线程C唤醒继续执行。
总结:此文章是假设三个线程按照顺序执行并且中间抢占资源都没有成功也没有发生中断,只是使用一种最简单的方法来理解ReentrantLock的流程。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。