java.util.concurrent.Semaphore
介绍:
Semaphore是一个信号灯模型,简单理解为N进N出的模型。每次调用acquire时,如果已经有N个线程进入管道,则会阻塞。每次线程离开管道时,通过release释放掉。当Semaphore的count为1时,它的语义就差不多是个互斥锁了,一进一出。
//JDK中的 例子,通过一个Semphore数组来控制线程池数量。
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 = ... 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;
}
}