java的信号量Semaphore经常用来限制只能有至多特定数量的线程操作某个资源,若取不到信号量的令牌刚需要等待有可用的令牌才能对资源进行操作。
//==================================================================================
使用信号量Semaphore的例子,比例java文档提供的例子,使用信号量来控制对池里的东西操作。
//信号量
public class Semaphore implements java.io.Serializable {
/** All mechanics via AbstractQueuedSynchronizer subclass */
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer {
//。。
}
static final class NonfairSync extends Sync {
//..
}
static final class FairSync extends Sync {
//..
}
//permits:信号量设置令牌的数量
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
//构造函数提供参数供选择公平或者不公平锁
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
//获取令牌
//如果可以获得一个令牌,则令牌数量递减1,方法返回;
//如果没有令牌可以获得,则线程会一直阻塞直到有令牌可以获得;
//当线程被中断时,方法会抛出InterruptedException异常
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//获取令牌
//如果可以获得一个令牌,则令牌数量递减1,方法返回;
//如果没有令牌可以获得,则线程会一直阻塞直到有令牌可以获得;
//当线程被中断时,它会继续等待令牌,不过它获得令牌的时间可能会改变。
public void acquireUninterruptibly() {
sync.acquireShared(1);
}
//获取令牌
//如果可以获得一个令牌,则令牌数量递减1,方法返回true;
//如果没有令牌可以获得,则不会等待并返回false;
//即使策略是公平锁,而且有其他线程在等待令牌的情况下,而刚好有一个可用的令牌,这个方法也可以获得令牌并返回true;
public boolean tryAcquire() {
return sync.nonfairTryAcquireShared(1) >= 0;
}
//获取令牌
//如果有令牌可用,马上获得一个令牌并且令牌数量递减1,方法返回true;
//如果没有令牌可以获得,则等待指定的时间,在超时之前如果有可用令牌则获得返回true,如果超时了还没有可用令牌则返回false;
//在超时时间内线程被中断会抛出InterruptedException异常
public boolean tryAcquire(long timeout, TimeUnit unit)throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
//释放令牌,信号号的令牌数量递增1
public void release() {
sync.releaseShared(1);
}
//获取指定数量的令牌
//如果有可用的指定数量令牌,则令牌数量减少指定的数量,方法马上返回;
//如果没有指定数量的令牌可用,则线程一起阻塞等待到有可用的指定数量令牌;
//当线程被中断是会抛出InterruptedException异常
//当指定数量是负数,则抛出IllegalArgumentException异常
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
//获取指定数量的令牌(跟方法acquireUninterruptibly()有点相似)
//如果有可用的指定数量令牌,则令牌数量减少指定的数量,方法马上返回;
//如果没有指定数量的令牌可用,则线程一起阻塞等待到有可用的指定数量令牌;
//当线程被中断,线程不会抛出InterruptedException异常,线程会继续排队(排除位置不变)等待有足够可用的数量令牌
//当指定数量是负数,则抛出IllegalArgumentException异常
public void acquireUninterruptibly(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireShared(permits);
}
//获取令牌(跟方法tryAcquire()相似)
//如果可以获得permits个令牌,则令牌数量递减permits,方法返回true;
//如果没有令牌可用的数量没有permits个,则不会等待并返回false;
//即使策略是公平锁,而且有其他线程在等待令牌的情况下,而刚好有permits个可用的令牌,这个方法也可以优先获得令牌并返回true;
//当permits是负数,则抛出IllegalArgumentException异常
public boolean tryAcquire(int permits) {
if (permits < 0) throw new IllegalArgumentException();
return sync.nonfairTryAcquireShared(permits) >= 0;
}
//获取令牌(跟方法tryAcquire(long timeout, TimeUnit unit)相似)
public boolean tryAcquire(int permits, long timeout, TimeUnit unit)throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
}
//释放令牌(跟方法release()相似)
public void release(int permits) {
if (permits < 0) throw new IllegalArgumentException();
sync.releaseShared(permits);
}
/**
* Returns the current number of permits available in this semaphore.
*/
public int availablePermits() {
return sync.getPermits();
}
/**
* Acquires and returns all permits that are immediately available.
*/
public int drainPermits() {
return sync.drainPermits();
}
/**
* Shrinks the number of available permits by the indicated
* reduction. This method can be useful in subclasses that use
* semaphores to track resources that become unavailable. This
* method differs from {@code acquire} in that it does not block
* waiting for permits to become available.
*/
protected void reducePermits(int reduction) {
if (reduction < 0) throw new IllegalArgumentException();
sync.reducePermits(reduction);
}
}
//==================================================================================
使用信号量Semaphore的例子,比例java文档提供的例子,使用信号量来控制对池里的东西操作。
class Pool {
private static final int MAX_AVAILABLE = 100;
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
public Object getItem() throws InterruptedException {
available.acquire();
return getNextAvailableItem();
}
public void putItem(Object x) {
if (markAsUnused(x))
available.release();
}
// Not a particularly efficient data structure; just for demo
protected Object[] items = new Object[10];//... whatever kinds of items being managed
protected boolean[] used = new boolean[MAX_AVAILABLE];
protected synchronized Object getNextAvailableItem() {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (!used[i]) {
used[i] = true;
return items[i];
}
}
return null; // not reached
}
protected synchronized boolean markAsUnused(Object item) {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (item == items[i]) {
if (used[i]) {
used[i] = false;
return true;
} else
return false;
}
}
return false;
}
}
//==================================================================================