基于信号量的有界缓存

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值