AQS源碼閱讀筆記(一)
阿新 • • 發佈:2018-04-13
har cond 重要 turn AD red 靜態 nbsp his
AQS源碼閱讀筆記
先看下這個類張非常重要的一個靜態內部類Node。如下:
static final class Node { //表示當前節點以共享模式等待鎖 static final Node SHARED = new Node(); //表示當前模式以獨占模式等待鎖 static final Node EXCLUSIVE = null; //表示當前線程等待鎖的動作被取消了(那麽當前節點將會在下一次叠代節點的時候被踢出) static final int CANCELLED = 1; //表示當前節點處於掛起狀態,如果當前節點的前一個節點釋放了鎖,那麽當前節點將會被喚醒 static final int SIGNAL = -1; //(此處先不分析,後續在分析COnfition的時候再分析) static final int CONDITION = -2; //此處我們先不分析,後續在分析釋放鎖的時候分析 static final int PROPAGATE = -3; //當前節點的狀態 volatile int waitStatus; //指向當前節點前一個節點的引用 volatile Node prev; //指向當前節點後一個節點的引用 volatile Node next; //當前節點持有的線程 volatile Thread thread; //當前節點以何種方式等待鎖(它的取值,要麽是SHARE,要麽是EXCLUSIVE) Node nextWaiter; //當前線程是否以共享模式等待鎖 final boolean isShared() { return nextWaiter == SHARED; } //查找當前節點的前一個節點 final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; } Node() { // Used to establish initial head or SHARED marker } Node(Thread thread, Node mode) { // Used by addWaiter this.nextWaiter = mode; this.thread = thread; } Node(Thread thread, int waitStatus) { // Used by Condition this.waitStatus = waitStatus; this.thread = thread; } }
接著,我們再來看看AQS中的字段:
private transient volatile Node head; private transient volatile Node tail; private volatile int state;
其中, node和tail分別表示頭結點和尾節點,這兩個字段是用來的保證同步隊列原子入(出)隊操作(具體後續在分析具體的實現類中說)。
state在此處可以簡單理解為加鎖的次數(每次加鎖,state + 1,每次釋放鎖, state - 1,當state = 0的時候,就表示沒有線程持有鎖 )。
後續結合具體的實現類來分析各種加鎖,解鎖。
AQS源碼閱讀筆記(一)