staticfinalclassFairSyncextendsSync{ finalvoidlock(){ // 获取锁 acquire(1); } publicfinalvoidacquire(int arg){ // 尝试获取锁 if (!tryAcquire(arg) && // 尝试获取锁失败 获取队列 并将 线程信息添加到队列 acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } // 尝试获取锁 protectedfinalbooleantryAcquire(int acquires){ final Thread current = Thread.currentThread(); // 默认 state 是 0 int c = getState(); if (c == 0) { // 判断队列情况 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) thrownew Error("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; }
// 是否有队列 publicfinalbooleanhasQueuedPredecessors(){ // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Node t = tail; // Read fields in reverse initialization order Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }
线程A :通过调用acquire(1)获取锁:
1:线程A 通tryAcquire(1)尝试获取锁,因为线程A 第一个来获取锁的,当前AQS 中的 state = 0
publicvoidunlock(){ sync.release(1); } publicfinalbooleanrelease(int arg){ if (tryRelease(arg)) { Node h = head; // 前面等待的时候,已经将前面的节点的 waitStatus 全部改为了Node.SIGNAL if (h != null && h.waitStatus != 0) // 唤醒线程 unparkSuccessor(h); returntrue; } returnfalse; } //尝试释放锁( 通过计算 state ) protectedfinalbooleantryRelease(int releases){ int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) thrownew IllegalMonitorStateException(); boolean free = false; if (c == 0) { free = true; // 释放线程引用 setExclusiveOwnerThread(null); } setState(c); return free; } // 唤醒线程 privatevoidunparkSuccessor(Node node){ int ws = node.waitStatus; if (ws < 0) compareAndSetWaitStatus(node, ws, 0);
Node s = node.next; if (s == null || s.waitStatus > 0) { s = null; // 循环找到链表 第二个位置的Node 唤醒该节点中的线程 for (Node t = tail; t != null && t != node; t = t.prev) if (t.waitStatus <= 0) s = t; } if (s != null) //唤醒线程 LockSupport.unpark(s.thread); }
/** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ finalvoidlock(){ if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); }
/** * Fair version of tryAcquire. Don't grant access unless * recursive call or no waiters or is first. */ protectedfinalbooleantryAcquire(int acquires){ final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) thrownew Error("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; } } //非公平锁的 尝试获取锁方法 finalbooleannonfairTryAcquire(int acquires){ final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); returntrue; } } elseif (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow thrownew Error("Maximum lock count exceeded"); setState(nextc); returntrue; } returnfalse; }
// 如果放回false 说明队列只有一个空 head节点 或者 队列是为空 //如果返回ture 说明 队列有线程正在排队 publicfinalbooleanhasQueuedPredecessors(){ // The correctness of this depends on head being initialized // before tail and on head.next being accurate if the current // thread is first in queue. Node t = tail; // Read fields in reverse initialization order Node h = head; Node s; return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); }