1 Semaphore.Sync內(nèi)部類
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L;
Sync(int permits) {
setState(permits);
}
final int getPermits() {
return getState();
}
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
// 如果remaining小于0旁壮,返回值小于0
// 如果remaining等于0祭阀,嘗試進(jìn)行CAS操作必指;如果CAS操作成功侄非,返回值等于0
// 如果remaining大于0蛤虐,嘗試進(jìn)行CAS操作;如果CAS操作成功灾前,返回值大于0
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
protected final boolean tryReleaseShared(int releases) {
for (;;) {
int current = getState();
int next = current + releases;
// 如果releases小于0
if (next < current)
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))
return true;
}
}
final void reducePermits(int reductions) {
for (;;) {
int current = getState();
int next = current - reductions;
// 如果reductions小于0
if (next > current)
throw new Error("Permit count underflow");
if (compareAndSetState(current, next))
return;
}
}
final int drainPermits() {
for (;;) {
int current = getState();
// 如果current等于0胯盯,返回值等于0
// 如果current大于0,嘗試進(jìn)行CAS操作山叮;如果CAS操作成功八堡,返回值大于0
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}
2 Semaphore.NonfairSync內(nèi)部類
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
NonfairSync(int permits) {
super(permits);
}
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
}
3 Semaphore.FairSync內(nèi)部類
static final class FairSync extends Sync {
private static final long serialVersionUID = 2014338818796000944L;
FairSync(int permits) {
super(permits);
}
protected int tryAcquireShared(int acquires) {
for (;;) {
// 如果其它線程所在節(jié)點(diǎn)入隊成功,返回值等于-1
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
// 如果remaining小于0聘芜,返回值小于0
// 如果remaining等于0兄渺,CAS操作成功,返回值等于0
// 如果remaining大于0汰现,CAS操作成功挂谍,返回值大于0
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
}
4 Semaphore
4.1 Semaphore中的字段
private final Sync sync;
4.2 Semaphore中的構(gòu)造方法
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
4.3 Semaphore中的其它方法
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public void acquireUninterruptibly() {
sync.acquireShared(1);
}
public boolean tryAcquire() {
return sync.nonfairTryAcquireShared(1) >= 0;
}
public boolean tryAcquire(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
public void release() {
sync.releaseShared(1);
}
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
public void acquireUninterruptibly(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireShared(permits);
}
public boolean tryAcquire(int permits) {
if (permits < 0) throw new IllegalArgumentException();
return sync.nonfairTryAcquireShared(permits) >= 0;
}
public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
}
public void release(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.releaseShared(permits);
}
public int availablePermits() {
return sync.getPermits();
}
public int drainPermits() {
return sync.drainPermits();
}
protected void reducePermits(int reduction) {
if (reduction < 0) throw new IllegalArgumentException();
sync.reducePermits(reduction);
}
public boolean isFair() {
return sync instanceof FairSync;
}
public final boolean hasQueuedThreads() {
return sync.hasQueuedThreads();
}
public final int getQueueLength() {
return sync.getQueueLength();
}
protected Collection<Thread> getQueuedThreads() {
return sync.getQueuedThreads();
}
public String toString() {
return super.toString() + "[Permits = " + sync.getPermits() + "]";
}
5 Semaphore使用案例
Semaphore通常用于限制并發(fā)訪問某些資源的線程數(shù)量叔壤。
場景:老師需要班上10個學(xué)生到講臺上填寫一張表,但是老師只有5支筆口叙,因此同一時刻只能保證5個學(xué)生拿到筆進(jìn)行填寫炼绘,沒有拿到筆的學(xué)生只能等前面的學(xué)生填寫完畢,再去拿筆進(jìn)行填寫妄田。
public class SemaphoreDemo {
// 5支筆
private static Semaphore semaphore = new Semaphore(5, true);
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
// 10個學(xué)生
for (int i = 0; i < 10; i++) {
service.execute(() -> {
try {
System.out.println(Thread.currentThread().getName() + " 同學(xué)想要拿到筆===");
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 同學(xué)拿到筆---");
System.out.println(Thread.currentThread().getName() + " 同學(xué)填寫中...");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName() + " 同學(xué)填寫完畢俺亮,馬上歸還筆。疟呐。脚曾。");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
});
}
service.shutdown();
}
}