计数信号量用来控制同时访问某个特定资源的操作数或同时执行某个指定操作的数量
A counting semaphore.Conceptually, a semaphore maintains a set of permits. Each acquire blocks if necessary until a permit is available, and then takes it. Each release adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
从概念上来说,Semaphore中维护了一组许可,许可的数量在构造函数中指定。acquire方法将获取一个可用的许可,如果没有可用的许可,该方法会被阻塞,直到Semaphore中有可用的许可。release方法释放一个许可,如果此时存在阻塞中的acqure方法,将释放一个阻塞中的acquire
事实上,Semaphore中只维护可用请求数量,并不包含实际的许可对象
在初始化Semaphore时可以设置其公平性,如果为公平Semaphore,则按照请求时间获得许可,即先发送的请求先获得许可,如果为非公平Semaphore,则先发送的请求未必先获得许可,这有助于提高程序的吞吐量,但是有可能导致某些请求始终获取不到许可(tryAcquire方法不使用公平性设置)
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
public class Test implements Runnable{
private static CountDownLatch latch = new CountDownLatch(1);
private static Semaphore semaphore = new Semaphore(2, true);
public void run(){
try {
latch.await();
this.work();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void work() throws InterruptedException{
// 如果等待acquire的线程过多,则终止后续线程的运行
if(semaphore.getQueueLength() > 2){
System.out.println("Too many thread waiting to acquire" + Thread.currentThread().getName());
return;
}
semaphore.acquire();
System.out.println("acquired by " + Thread.currentThread().getName());
Thread.sleep(1*1000);
semaphore.release();
}
public static void main(String[] args) throws Exception{
for(int i = 0 ; i < 10 ; i++){
Thread t = new Thread(new Test());
t.start();
}
//保证所有线程同时运行
latch.countDown();
}
}
运行结果如下:
acquired by Thread-9
Too many thread waiting to acquireThread-7
Too many thread waiting to acquireThread-3
Too many thread waiting to acquireThread-5
Too many thread waiting to acquireThread-6
acquired by Thread-1
Too many thread waiting to acquireThread-8
acquired by Thread-2
acquired by Thread-0
acquired by Thread-4