留意:并非一定要执行acquire()方法的线程才能调用release()方法,任意一个线程都可以调用release()方法,也可以通过reducePermits()方法来减少令牌数。
[code]public class Semaphore implements java.io.Serializable { private final Sync sync; //Creates a Semaphore with the given number of permits and nonfair fairness setting. public Semaphore(int permits) { sync = new NonfairSync(permits); } //Releases a permit, returning it to the semaphore. public void release() { //执行AQS的模版方法releaseShared() sync.releaseShared(1); } //Synchronization implementation for semaphore. //Uses AQS state to represent permits. Subclassed into fair and nonfair versions. abstract static class Sync extends AbstractQueuedSynchronizer { Sync(int permits) { //设置state的值为传入的令牌数 setState(permits); } //实验释放锁,也就是对state值举行累加 protected final boolean tryReleaseShared(int releases) { for (;;) { int current = getState(); int next = current + releases; if (next < current) { throw new Error("Maximum permit count exceeded"); } if (compareAndSetState(current, next)) { return true; } } } ... } ...}public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { ... //Releases in shared mode. //Implemented by unblocking one or more threads if #tryReleaseShared returns true. public final boolean releaseShared(int arg) { //执行Semaphore的内部类Sync实现的tryReleaseShared()方法,释放共享锁 if (tryReleaseShared(arg)) { //执行AQS的doReleaseShared()方法,唤醒等待队列中的线程 doReleaseShared(); return true; } return false; } //Release action for shared mode -- signals successor and ensures propagation. //Note: For exclusive mode, release just amounts to calling unparkSuccessor of head if it needs signal. private void doReleaseShared() { for (;;) { //每次循环时头结点都会发生变化 //因为调用unparkSuccessor()方法会唤醒doAcquireSharedInterruptibly()方法中阻塞的线程 //然后阻塞的线程会在执行setHeadAndPropagate()方法时通过setHead()修改头结点 Node h = head;//获取最新的头结点 if (h != null && h != tail) {//等待队列中存在挂起线程的结点 int ws = h.waitStatus; if (ws == Node.SIGNAL) {//头结点的状态正常,表现对应的线程可以被唤醒 if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0)) { continue;//loop to recheck cases } //唤醒头结点的后继结点 //唤醒的线程会在doAcquireSharedInterruptibly()方法中执行setHeadAndPropagate()方法修改头结点 unparkSuccessor(h); } else if (ws == 0 && !compareAndSetWaitStatus(h, 0, Node.PROPAGATE)) { //假如ws = 0表现初始状态,则修改结点为PROPAGATE状态 continue;//loop on failed CAS } } if (h == head) {//判断头结点是否有变化 break;//loop if head changed } } } //Wakes up node's successor, if one exists. private void unparkSuccessor(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; for (Node t = tail; t != null && t != node; t = t.prev) { if (t.waitStatus 0L) { nanos = trip.awaitNanos(nanos); } } catch (InterruptedException ie) { if (g == generation && ! g.broken) { breakBarrier(); throw ie; } else { Thread.currentThread().interrupt(); } } if (g.broken) { throw new BrokenBarrierException(); } if (g != generation) { return index; } if (timed && nanos