是什么
Semaphore 翻译过来就是信号量的意思。它类似一个资源池(读者可以类比线程池),每个线程需要调用 acquire() 方法获取资源,然后才能执行,执行完后,需要 release 资源,让给其他的线程用。
大概大家也可以猜到,Semaphore 其实也是 AQS 中共享锁的使用,因为每个线程共享一个池嘛。
怎么用
由上可知, Semaphore 最重要的两个方法就是 acquire() 和 release()。
初始化 Semaphore
public Semaphore(int permits, boolean fair) {sync = fair ? new FairSync(permits) : new NonfairSync(permits);}
可以看到 Semaphore 也是利用了 Sync,一个基于 AQS 实现的同步器来完成相关操作的。初始化时也可以指定使用公平锁还是非公平锁。
acquire() 方法
public void acquire() throws InterruptedException {sync.acquireSharedInterruptibly(1);}public final void acquireSharedInterruptibly(int arg)throws InterruptedException {if (Thread.interrupted())throw new InterruptedException();if (tryAcquireShared(arg) < 0)doAcquireSharedInterruptibly(arg);}private void doAcquireSharedInterruptibly(int arg)throws InterruptedException {final Node node = addWaiter(Node.SHARED);boolean failed = true;try {for (;;) {final Node p = node.predecessor();if (p == head) {int r = tryAcquireShared(arg);if (r >= 0) {setHeadAndPropagate(node, r);p.next = null; // help GCfailed = false;return;}}if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())throw new InterruptedException();}} finally {if (failed)cancelAcquire(node);}}
可以看出上面的方法和 countDownLatch 几乎是一模一样的,除了 tryAcquireShared 获取共享锁这个方法分为公平和非公平模式。
公平模式的 tryAcquireShared
protected int tryAcquireShared(int acquires) {
for (;;) {
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
非公平模式的 tryAcquireShared
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
可以看出公平模式和非公平模式的区别还是在于判断队列中是否有节点。
上面的代码总结为:
由于 tryAcquireShared(arg) 返回小于 0 的时候,说明 state 已经小于 0 了(没资源了),此时 acquire 不能立马拿到资源,需要进入到阻塞队列等待。
公平模式和非公平模式的区别
在实际应用中,如果使用公平模式的话,假设一个资源已经为0,那么后面执行 acquire() 的线程就会阻塞(插入到等待队列中),但这个资源大于0时,按入队的顺序取出线程来获取这个资源,别的线程不能插队。
如果是非公平模式的话,执行 acquire() 的线程不必先看是否队列中已有线程在排队,而可以直接获得该资源。
release()
public void release() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
// release 总是为1,和 countDown 不同的是,这里是加1,而 countDown 是减1
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
// 溢出越界
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
private void doReleaseShared() {
for (;;) {
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
unparkSuccessor(h);
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
可以看出 Release 不区分公平和非公平模式。其他的和 countDown 是一样的。注意这里获取的资源总是为 1(sync.releaseShared(1);)。
注意
当执行 doReleaseShared 的时候会唤醒等待队列中的第一个线程,然后如果线程如果判断 r = tryAcquireShared(arg) >= 0 即资源还有剩余,会继续唤醒第二个线程,以此类推。
而在 CountDownLatch 中,执行了 doReleaseShared 后会唤醒所有的等待线程,因为到最后一个线程执行完 countDown() 方法后,r 就一直会是 0 了。因此可以一个接着一个线程被唤醒。
