AQS线程状态:
/** waitStatus value to indicate thread has cancelled */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should unconditionally propagate
*/
static final int PROPAGATE = -3;
复制代码
1、acquire函数分析
1、如果tryAcquire操作成功,则获取锁成功,直接返回
2、如果tryAcquire操作失败,则先执行addWaiter(Node.EXCLUSIVE)函数,再执行acquireQueued(node,arg)
函数;
3、如果acquireQueued返回true,说明当前线程是可以中断,则执行selfInterrupt(),设置当前线程为可中断;
public final void acquire(int arg) {
if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
复制代码
2、tryAcquire函数分析
protected boolean tryAcquire(int unused) {
//CAS操作,更新成功,则设置线程独占,返回true
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
复制代码
3、addWaiter(Node.EXCLUSIVE)函数分析
1、新建一个EXCLUSIVE模式的节点;
2、将当前tail节点作为一个前置节点pred;
3、如果pred不为空,说明存在tail节点,则将当前node的前置节点设置为pred,
并CAS操作将当前的node节点设置为新的tail节点,然后pred的后置节点next指向node节点,
返回新的tail节点node;
4、如果pred为空,则执行end(node)函数;
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;
}
复制代码
5、end函数,无限循环操作,获取tail节点,
如果tail为空,则CAS操作,创建一个空的Head节点;并设置给tail;
6、如果tail不为空,则将当前节点的前置节点prev设置为tail节点,并CAS操作设置当前节点node为新的tail节点,且设置旧tail节点的next为node节点,返回新的tail节点;
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;
}
}
}
}
复制代码
4、acquireQueued(node, arg)函数分析
1、定义2个flag,分别标记是否执行取消抢锁、是否标记中断;此代码无限循环,
直到线程获取到锁、或者取消抢锁才返回
2、获取当前节点的前置节点p;
3、如果前置节点是head节点,说明当前node前面没有节点在等待获取锁资源,则可以尝试抢锁:
如果抢锁成功,则将当前node设置为head节点,将前置节点p的next节点设置为null,
以便GC回收,并将取消抢锁flag设置为false,不执行finally代码,返回中断flag=false;
4、如果前置节点p不是head节点,或者抢锁失败,则执行:
shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt();
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;
}
//节点p不是head节点,或者抢锁失败,执行这里,挂起当前线程
if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())
interrupted = true;
}
} finally {
//如果挂起现场异常,则执行取消抢锁操作
if (failed)
cancelAcquire(node);
}
}
复制代码
5、获取前置节点的状态,如果状态是SIGNAL(SIGNAL表示释放锁之后,立马会唤醒后继节点),
则直接返回true;
6、如果ws>0,表示当前节点的状态为CANCELLED,则需要找到前置节点中不为CANCELLED
的节点pred,并将此pred节点的next节点设置为当前node节点,返回false;
7、如果ws<=0,则将pred节点的状态设置为SIGNAL,返回false;
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;
}
复制代码
8、挂起当前线程,返回中断标记true;
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
复制代码
5、cancelAcquire(Node node)函数解析
1、如果node节点为空,则直接返回;
2、如果node不为空,则设置node的线程为空;
3、获取当前node的前置节点pred,并判断pred节点的状态,如果大于0(取消状态),则循环往前查找,
找到非取消状态的node为止,并将其设置为node新的前置节点;
4、获取pred的next节点predNext,设置当前node状态为CANCELLED;
5、如果当前node是tail节点,则直接CAS操作,将pred节点设置为新的tail节点,操作成功,
则将pred的next节点设置为空;
6、如果node不是tail节点,或者CAS设置tail失败,则判断:
6.1、如果pred节点不是head节点,且节点状态是SIGNAL状态,且线程不为空,则获取node的next节点,
如果next节点不为空,且状态小于0(非取消状态),则将pred的next节点设置为node的next节点;
6.2、如果pred节点是head节点,或者状态不是SIGNAL,或则线程为空,则调用unparkSuccessor函数,
唤醒后续线程,防止队列挂掉;
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head
&&
(
(ws = pred.waitStatus) == Node.SIGNAL
||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))
)
&& pred.thread != null
) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
复制代码