用途:用来控制同时访问某个特定资源的操作数量,或者同时执行某个指定操作的数量。计数信号量可以用来实现某种资源池,或者对容器施加边界。
public class SemaphoreTest<T> {
private final Set<T> set;
private final Semaphore sema;
public SemaphoreTest(int bound){
this.set = Collections.synchronizedSet(new HashSet<T>());
this.sema = new Semaphore(bound);
}
public boolean add(T o) throws InterruptedException{
sema.acquire();
boolean wasAdded = false;
try{
wasAdded = set.add(o);
return wasAdded;
}finally{
if(!wasAdded){
sema.release();
}
}
}
public boolean remove(T o){
boolean wasRemoved = set.remove(o);
if(wasRemoved){
sema.release();
}
return wasRemoved;
}
public static void main(String[] args) throws InterruptedException{
int permits = 5;
int elements = permits + 1;
SemaphoreTest<Integer> test = new SemaphoreTest<Integer>(permits);
for(int i = 0;i < elements; i++){
test.add(i);
}
}
}
由于实际待添加的元素个数大于信号量所允许的数量,因此最后一次添加时,会一直阻塞。