僅爲個人複習筆記,格式之類的未調整,明天抽空再整下。
1、acquire函數
// 首先調用子類的tryAcquire函數,執行具體的操作
// 如果失敗了,執行addWaiter 加入阻塞隊列尾部
// 接着執行acquireQueued 嘗試再次檢查前面的線程是不是完事了,自旋再嘗試一下
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
// 這個函數的特點,就是會設置一個哨兵節點,負責放哨,比如說標記下後面的節點是不是有需要喚醒的,
// 如果後面是有節點需要喚醒的 那麼這個哨兵節點的值就是SIGAL
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;
}
// 這個函數分三部分
// 第一部分就是一進去之後,先看下pre節點是不是head了,如果是那就意味着輪到自己了,就再次嘗試去CAS,如果成功就直接返回了
// 第二部分,首先會執行shouldParkAfterFailedAcquire函數,判斷一下是不是可以進入阻塞狀態,如果判斷是true,那麼就調用parkAndCheckInterrupt掛起當前線程
// 第三部分就是finally塊裏面的,當出現了異常的時候,failed沒有正常被修改爲true,就進入這個finally塊,
// 注意這裏只有try/finally,沒有catch,異常是會往上拋的,所以這段代碼的意思就是,一旦出現非預期的異常,直接取消當前節點的acquire,然後向上拋出異常
final boolean acquireQueued(final Node node, long 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);
}
}
// 這段代碼核心就是,設置前面個節點的狀態爲SIGNAL,
// 因爲哨兵節點的初始waitStatus=0,所以第一個入隊的節點需要設置哨兵的狀態爲SIGAL,標識着後面有節點需要喚醒
// 所以這裏只有前一個節點狀態爲SIGNAL的時候,纔會返回true 然後掛起自己
// 如果檢查到ws>0,大於0的只有CALLELED狀態,所以直接向前檢查有哪些CALLED狀態的,直接跳過
// 如果前一個節點不是SIGNAL,那麼就設置它爲SIGNAL,再返回檢查一下,是不是輪到當前線程了,如果不是再回來掛起
// 所以這個函數決定了,會自旋兩次,檢查是不是輪到自己了
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;
}
// 最後就是這個掛起函數,返回了一個線程中斷的標識,
// 如果這個線程park返回的原因是因爲當前線程被中斷了,那麼因爲park的原因直接返回了,沒起到效果
// 所以就直接退出去,在上層設置自己被中斷了,在最後tryAcquire執行成功之後,調用selfInterrupt()把自己中斷,以達到原本預期的中斷效果。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
最後就是release函數
// 這個函數也是執行子類的tryRelease實現,如果執行失敗就返回false,如果成功就去喚醒阻塞隊列的下一個等待的Node
// 需要注意的是這裏執行喚醒的判斷代碼 [h.waitStatus != 0] head的初始值是0,這裏是只有不爲0纔去喚醒,這裏就和上面的設置SIGNAL關聯起來了
// 明白了爲啥一定要設置前面的Node爲SIGNAL之後才能掛起,就是爲了標識後面有需要喚醒的Node
public final boolean release(long arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
// 這裏就分兩步 第一步去修改head節點的狀態,重新修改爲0
// 接着就去喚醒next節點,如果next節點不滿足,就從後往前遍歷,找到第一個滿足條件的,也就是狀態>0的節點,去喚醒該Node的thread
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,然後追加在條件隊列尾部
// 然後通過[while (!isOnSyncQueue(node))] 避免線程被虛假喚醒
// 這個節點是不在同步隊列中的,所以一進來就會被掛起
// 直到等到被喚醒,然後發現自己已經在同步隊列中了,所以執行acquireQueued去嘗試競爭
// 如果競爭失敗,則被掛在同步隊列中
public final void await() throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
Node node = addConditionWaiter();
long savedState = fullyRelease(node);
int interruptMode = 0;
while (!isOnSyncQueue(node)) {
LockSupport.park(this);
if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
break;
}
if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
interruptMode = REINTERRUPT;
if (node.nextWaiter != null) // clean up if cancelled
unlinkCancelledWaiters();
if (interruptMode != 0)
reportInterruptAfterWait(interruptMode);
}
// 再看看這個喚醒的函數,其實就是取出第一個Node,然後解鏈,然後放到AQS同步隊列中,喚醒該Node的線程
private void doSignal(Node first) {
do {
if ( (firstWaiter = first.nextWaiter) == null)
lastWaiter = null;
first.nextWaiter = null;
} while (!transferForSignal(first) &&
(first = firstWaiter) != null);
}
// 這個函數就是把狀態給改成0,然後入隊,喚醒Node線程
final boolean transferForSignal(Node node) {
/*
* If cannot change waitStatus, the node has been cancelled.
*/
if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
return false;
/*
* Splice onto queue and try to set waitStatus of predecessor to
* indicate that thread is (probably) waiting. If cancelled or
* attempt to set waitStatus fails, wake up to resync (in which
* case the waitStatus can be transiently and harmlessly wrong).
*/
Node p = enq(node);
int ws = p.waitStatus;
if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
LockSupport.unpark(node.thread);
return true;
}
參考鏈接: