基于信号量的有界缓存
public class BoundedBuffer<E>
{
private final Semaphore availableItems, availableSpaces;
private final E[] items;
private int putPositon = 0, takePosition = 0;
@SuppressWarnings("unchecked")
public BoundedBuffer(int capacity)
{
availableItems = new Semaphore(capacity);
availableSpaces = new Semaphore(capacity);
items = (E[])new Object[capacity];
}
public boolean isEmpty()
{
return availableItems.availablePermits() == 0;
}
public boolean isFull()
{
return availableSpaces.availablePermits() == 0;
}
public void put(E x)
throws InterruptedException
{
availableSpaces.acquire();
doInsert(x);
availableItems.release();
}
public E take()
throws InterruptedException
{
availableItems.acquire();
E item = doExtract();
availableSpaces.release();
return item;
}
private synchronized void doInsert(E x)
{
int i = putPositon;
items[i] = x;
putPositon = (++i == items.length) ? 0 : 1;
}
private synchronized E doExtract()
{
int i = takePosition;
E x = items[i];
items[i] = null;
takePosition = (++i == items.length) ? 0 : i;
return x;
}
}
补充:综合编程 , 其他综合 ,