/** * Base of synchronization control for this lock. Subclassed * into fair and nonfair versions below. Uses AQS state to * represent the number of holds on the lock. */ abstractstaticclassSyncextendsAbstractQueuedSynchronizer {//是父类,子类实现包含非公平和公平两种的静态内部类。 privatestaticfinallongserialVersionUID= -5179523762034025860L;
/** * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. */ abstractvoidlock();
/** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ finalbooleannonfairTryAcquire(int acquires) {//非公平的获取锁,一次尝试 finalThreadcurrent= Thread.currentThread(); intc= getState();//首先拿到锁的标识位volite修饰的。 if (c == 0) {//如果是0表示没有被占用 if (compareAndSetState(0, acquires)) {//通过CAS方式set为1, setExclusiveOwnerThread(current);//将占用的标志位标识为当前线程 returntrue; } } elseif (current == getExclusiveOwnerThread()) {//如果状态位不为0,就表示已经被占用了,这时去判断是否是当前的线程,如果是的话就可重入。 intnextc= c + acquires;//标识位++; if (nextc < 0) // overflow(防止int型溢出为-) thrownewError("Maximum lock count exceeded"); setState(nextc);//已经被锁住了,只有当前线程能够拿到,所以可以不用cas,直接set returntrue; } returnfalse; }
protectedfinalbooleanisHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); }
final ConditionObject newCondition() { returnnewConditionObject(); }
/** * Reconstitutes the instance from a stream (that is, deserializes it). */ privatevoidreadObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); setState(0); // reset to unlocked state } }
/** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ finalvoidlock() { if (compareAndSetState(0, 1))//CAS修改锁的标识位 setExclusiveOwnerThread(Thread.currentThread());//给当前的线程分配锁 else acquire(1);//底层是AQS的acquire,但实现类其实就是下面的tryAcquire }
privatevoidunparkSuccessor(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. */ intws= 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. */ Nodes= 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); }