Semaphore的代码实例:
主要用于控制并发数。
import java.util.concurrent.*;
public class ThreadTest {
public static void main(String[] args) throws Exception {
//Semaphore可以选择公平队列或者非公平队列
//更多的是限流的作用,例如停车场:停满指定数量的车后就通知无车位,只有等到有车离开别的车才有地方停
Semaphore semaphore = new Semaphore(3, true);//提供三张凭证
for ( int i = 0; i < 4; i++) {
Thread.sleep(100);
new Thread(() -> {
try {
semaphore.acquire();//获取一张凭证
// semaphore.acquire(2);//获取两张凭证
System.out.println(Thread.currentThread().getName() + "进入停车场");
System.out.println("还剩停车位"+semaphore.availablePermits());
if(semaphore.availablePermits()==0){//没车位了
semaphore.release();//有一辆车开走了
Thread.sleep(1000);
}
} catch (Exception e) {
}
}).start();
}
Thread.sleep(2000);
System.out.println("程序运行完毕");
}
}
下面是Semaphore上述代码所引用到的源码及其说明:
Semaphore的底层是基于AQS(AbstractQueuedSynchronizer)
//构建Semaphore对象
private volatile int state; //有个volatile修饰的state
public Semaphore(int permits, boolean fair) {//构造方法可选择公平锁或者非公平锁,默认非
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
FairSync(int permits) {
super(permits);//给state设置值
}
Sync(int permits) {
setState(permits);
}
protected final void setState(int newState) {
state = newState;
}
protected final int getState() {
return state;
}
//获取凭证
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);//假如等待队列
}
protected int tryAcquireShared(int acquires) {
for (; ; ) {
if (hasQueuedPredecessors())//假如前面有等待对象,则说明凭证已经用完
return -1;
int available = getState(); //获取可用凭证数量(state的值)
int remaining = available - acquires; //减去被拿走的凭证
if (remaining < 0 ||
compareAndSetState(available, remaining))//基于CAS机制将剩余凭证数量更新到state中
return remaining;
}
}
///释放凭证
public void release() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
protected boolean tryReleaseShared(int arg) {
throw new UnsupportedOperationException();
}
protected final boolean tryReleaseShared(int releases) {
for (; ; ) {
int current = getState(); //获取可用凭证数量(state的值)
int next = current + releases; //加上释放的凭证数量
if (next < current) // overflow
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))//基于CAS设置回state
return true;
}
}