今天在学习线程中文章多次提到AQS这个框架,名字很熟悉但是他不认识我,我不认识他。
说干就干,来读一波AQS的源码吧
- ReentrantLock 中的lock方法
/**
* 1.通过CAS获取锁获取到设置当前线程为独占锁
* 2.获取不到继续获取锁
*
*/
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
/**
* 这一段做了三个事情下面是三个方法的详细代码
* tryAcquire:再次尝试获取锁,如果没有获取到锁返回false添加等待节点
* addWaiter:添加节点这里面维护了一个等待队列
* acquireQueued : cas自旋获取锁
*
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
// 如果当前状态为0代表没有锁占用
if (c == 0) {
// hasQueuedPredecessors 判断当前线程需不需要排队
// 不排队获取锁 获取锁成功设置为独占锁
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//判断当前线程是不是独占锁是的话更新锁的状态
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
//这样可以表示当前线程被锁了几次,后面的可重入锁中会用到
setState(nextc);
return true;
}
return false;
}
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;
}
- addWaiter把节点添加在了尾部 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);
}
}
- 为什么要判断他 你看 你经历了上面两步还是没有获取锁,那总不能放着不管了吧 得给你一个号让你排着等
当你拿到号了就去休息也就是堵塞等待着轮到你了被唤醒
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}