算法与数据结构-设计有限阻塞队列

设计有限阻塞队列

题目

leetcode原题:1188. 设计有限阻塞队列

实现一个拥有如下方法的线程安全有限阻塞队列:

  • BoundedBlockingQueue(int capacity) 构造方法初始化队列,其中capacity代表队列长度上限。
  • void enqueue(int element) 在队首增加一个element. 如果队列满,调用线程被阻塞直到队列非满。
  • int dequeue() 返回队尾元素并从队列中将其删除. 如果队列为空,调用线程被阻塞直到队列非空。
  • int size() 返回当前队列元素个数。

解析

阻塞队列,首先想到要使用ReetrantLock来实现锁,同时需要使用lock来创建两个的等待条件,一个是非空一个是非满,生产者线程等待非满条件入队,消费者线程等待非空条件出队。同时题目需求,入队在队首,出队在队尾,可以选择使用LinkList中的addFirst和removeLast来实现。

这样大框架就出来了。

代码

class BoundedBlockingQueue {

    private LinkedList<Integer> innerQueue;
    private int capacity;

    private ReentrantLock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public BoundedBlockingQueue(int capacity) {
        innerQueue = new LinkedList<Integer>();
        this.capacity = capacity;
    }
    
    public void enqueue(int element) throws InterruptedException {
        try{
            lock.lockInterruptibly();
            while(size() == capacity){
                notFull.await();
            }
            innerQueue.addFirst(element);
            notEmpty.signalAll();
        }finally{
            lock.unlock();
        }
    }
    
    public int dequeue() throws InterruptedException {
        try{
            lock.lockInterruptibly();
             while(size() == 0){
                notEmpty.await();
            }
            int result = innerQueue.removeLast();
            notFull.signalAll();
            return result;
        }finally{
            lock.unlock();
        }
    }
    
    public int size() {
        try{
            lock.lock();
            return innerQueue.size();
        }finally{
            lock.unlock();
        }
    }
}
原文地址:https://www.cnblogs.com/ging/p/14239631.html