并发包实现阻塞队列

/**
 * @描述: 阻塞队列 ,先放进来先取走
 * 缓冲区:隔离效果,平均每一秒钟收一个短信,放在池子里
 * 可以放可以取,当满了不能放,取走了之后才能取
 * 当空的时候不能取,只有放了之后才能取
 * @作者: Wnj .
 * @创建时间: 2017年5月16日 .
 * @版本: 1.0 .
 */
public class BoundedBuffer {
    
    final Lock lock = new ReentrantLock();
    
    //空 ,一个Condition有五个线程同时往池子里放,发现缓冲区满了,都阻塞了,结果有一个去取了,五个中有一个唤醒了,取完唤醒,那么只能唤醒取的,不能唤醒放的
    final Condition notFull = lock.newCondition();
    
    //
    final Condition notEmpty = lock.newCondition();
    
    final Object[] items = new Object[100];
    
    int putptr, takeptr, count;
    
    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            //如果格子已满
            while (count == items.length)
                notFull.await();
            items[putptr] = x;
            //指针
            if (++putptr == items.length)
                //从0开始放
                putptr = 0;
            //存入一个值的时候对count进行++
            ++count;
            notEmpty.signal();
        }
        finally {
            lock.unlock();
        }
    }
    
    public Object take() throws InterruptedException {
        lock.lock();
        try {
            //没有值的时候进行等待
            while (count == 0)
                notEmpty.await();
            Object x = items[takeptr];
            if (++takeptr == items.length)
                takeptr = 0;
            //取走一个值的时候对count--
            --count;
            //唤醒
            notFull.signal();
            return x;
        }
        finally {
            lock.unlock();
        }
    }
}

 

posted @ 2017-05-25 10:43  superGG  阅读(244)  评论(0编辑  收藏  举报