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();elsereturn p;}Node() { // Used to establish initial head or SHARED marker}Node(Thread thread, Node mode) { // Used by addWaiterthis.nextWaiter = mode;this.thread = thread;}Node(Thread thread, int waitStatus) { // Used by Conditionthis.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的時候,就表示沒有線程持有鎖 )。
后續結合具體的實現類來分析各種加鎖,解鎖。
?