/**
* Head of the wait queue, lazily initialized. Except for
* initialization, it is modified only via method setHead. Note:
* If head exists, its waitStatus is guaranteed not to be
* CANCELLED.
* 头节点,当前持有锁的线程
* */privatetransientvolatileNodehead;/**
* Tail of the wait queue, lazily initialized. Modified only via
* method enq to add new wait node.
* 阻塞的尾节点
*/privatetransientvolatileNodetail;/**
* The synchronization state.
* 锁状态(同步状态),0表示没有占用,大于0表示有线程持有锁,可重入锁可以大于1
* */privatevolatileintstate;
staticfinalclassNode{/** Marker to indicate a node is waiting in shared mode */// 共享模式 staticfinalNodeSHARED=newNode();/** Marker to indicate a node is waiting in exclusive mode */// 独占模式 staticfinalNodeEXCLUSIVE=null;//------- waitStatus的状态 /** waitStatus value to indicate thread has cancelled */// 此线程取消了争抢这个锁staticfinalintCANCELLED=1;/** waitStatus value to indicate successor's thread needs unparking */staticfinalintSIGNAL=-1;/** waitStatus value to indicate thread is waiting on condition */staticfinalintCONDITION=-2;/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
* */staticfinalintPROPAGATE=-3;/**
* 等待状态 上面的枚举值
* 大于0也就是1时,代表线程取消了等待,抢半天抢不到就不抢了
* */volatileintwaitStatus;/**
* 前驱节点
* */volatileNodeprev;/**
* 后继节点
*/volatileNodenext;/**
* The thread that enqueued this node. Initialized on
* construction and nulled out after use.
* 线程对象
* */volatileThreadthread;/**
*
* */NodenextWaiter;}
protectedfinalbooleantryAcquire(intacquires){/*
* Walkthrough:
* 1. If read count nonzero or write count nonzero
* and owner is a different thread, fail.
* 2. If count would saturate, fail. (This can only
* happen if count is already nonzero.)
* 3. Otherwise, this thread is eligible for lock if
* it is either a reentrant acquire or
* queue policy allows it. If so, update state
* and set owner.
**/Threadcurrent=Thread.currentThread();intc=getState();intw=exclusiveCount(c);if(c!=0){// (Note: if c != 0 and w == 0 then shared count != 0) if(w==0||current!=getExclusiveOwnerThread())returnfalse;if(w+exclusiveCount(acquires)>MAX_COUNT)thrownewError("Maximum lock count exceeded");// Reentrant acquire setState(c+acquires);returntrue;}if(writerShouldBlock()||!compareAndSetState(c,c+acquires))returnfalse;setExclusiveOwnerThread(current);returntrue;}
privateNodeaddWaiter(Nodemode){// 把线程包装成NodeNodenode=newNode(Thread.currentThread(),mode);// Try the fast path of enq; backup to full enq on failure// 开始尝试在尾部添加,1.当前节点的prev指向原来的尾节点;2.尾节点的next指向当前节点// 原来最后一个尾节点 准备作为当前节点的prev Nodepred=tail;// pred != null 也就是尾节点不是空 if(pred!=null){// pred也就是尾节点赋值给当前节点的prev node.prev=pred;// 通过cas把当前节点赋值给尾节点的next if(compareAndSetTail(pred,node)){// cas成功,实现了作为尾节点加入了链表 pred.next=node;returnnode;}}// 如果到这里,说明1.pred是空,或者说队列是空;2.cas失败// 开始执行enq方法,死循环竞争入队 enq(node);returnnode;}
privatestaticbooleanshouldParkAfterFailedAcquire(Nodepred,Nodenode){// 前驱节点的等待状态intws=pred.waitStatus;// 为SIGNAL 就是正常 返回if(ws==Node.SIGNAL)/*
* This node has already set status asking a release
* to signal it, so it can safely park.
* */returntrue;if(ws>0){// 前驱节点 waitStatus大于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不等于-1和1,那也就是只可能是0,-2,-3/*
* 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.
* */// 用CAS将前驱节点的waitStatus设置为Node.SIGNAL(也就是-1) 从等待队列加入同步队列?compareAndSetWaitStatus(pred,ws,Node.SIGNAL);}returnfalse;}
privatevoidunparkSuccessor(Nodenode){// node是head头节点/*
* 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.
* */intws=node.waitStatus;// head的等待状态小于0,改为0 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.
* */// 开始唤醒后继节点,但有可能后继节点取消了等待>0Nodes=node.next;if(s==null||s.waitStatus>0){s=null;// 循环从队尾一直向前找,找到最前面那个(不知道为什么不从头开始找?考虑并发吗?)for(Nodet=tail;t!=null&&t!=node;t=t.prev)if(t.waitStatus<=0)s=t;}if(s!=null)// 唤醒线程 LockSupport.unpark(s.thread);}