PDF
1Java(5)AQSContents ............................................................................................... 1 .................................................................................................... 2public abstract class AbstractQueuedSynchronizerextends AbstractOwnableSynchronizerimplements Serializable使getState()setState(int)compareAndSetState(int, int)tryAcquire(int)tryRelease(int)tryAcquireShared(int)tryReleaseShared(int)isHeldExclusively()线class Mutex implements Lock, java.io.Serializable { private static class Sync extends AbstractQueuedSynchronizer { protected boolean isHeldExclusively() { return getState() == 1; } public boolean tryAcquire(int acquires) { assert acquires == 1; // Otherwise unused if (compareAndSetState(0, 1)) { setExclusiveOwnerThread(Thread.currentThread()); return true; 2 } return false; } protected boolean tryRelease(int releases) { assert releases == 1; // Otherwise unused if (getState() == 0) throw new IllegalMonitorStateException(); setExclusiveOwnerThread(null); setState(0); return true; } } // ...}class Mutex implements Lock, java.io.Serializable { // ... private final Sync sync = new Sync(); // 11 public void lock() { sync.acquire(1); } public boolean tryLock() { return sync.tryAcquire(1); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } public boolean isLocked() { return sync.isHeldExclusively(); } public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1, unit.toNanos(timeout)); } }使 3acquire线线线线线public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt();}private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); Node pred = tail; // enq // 线enqenq if (pred != null) { node.prev = pred; if (compareAndSetTail(pred, node)) { // CAStailtailnodetailpred pred.next = node; return node; } } // enq1. 2.CAS enq(node); return node;}private Node enq(final Node node) { for (;;) { Node t = tail; if (t == null) { 4 // headtail if (compareAndSetHead(new Node())) tail = head; } else { node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } }}releasepublic final boolean release(int arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false;}

HTML view coming soon.

Download PDF for the full formatted version.