AQS是一種併發數據結構,node
以公平鎖的acquire爲例分析相關代碼數據結構
public final void acquire(int i){ if(!tryAcquired()&& acquireQueued(addWaiter(Node.EXCLUSIVE),arg)){ selfInterrrupt(); } }
獲取當前state if(state==0){ 無人佔用,則經過cas改變state狀態, 成功後,從新設置鎖的全部者; return true; }else{ if(當前線程=鎖的全部者){ state+=1;設置state; return true; } return false; }
final boolean acquireQueued(final Node node, int arg) { boolean interrupted = false; try { for (;;) {// 循環 final Node p = node.predecessor();// 獲取前一個節點 if (p == head && tryAcquire(arg)) { // 若是前一個節點是頭結點,表示當前節點合適去 tryAcquire setHead(node); // acquire 成功,則設置新的頭節點 p.next = null; // 將前面節點對當前節點的引用清空 return interrupted; } if (shouldParkAfterFailedAcquire(p, node)) // 檢查是否失敗後須要 park interrupted |= parkAndCheckInterrupt(); } } catch (Throwable t) { cancelAcquire(node);// 出現異常,取消 if (interrupted) selfInterrupt(); throw t; } }