The BoundedBlockingQueue(int Capacity) constructor initializes the queue, where capacity represents the upper limit of queue length. Void enQueue (int element) adds an element to the queue. If the queue is full, the calling thread blocks until the queue is not full. Int dequeue() returns the last element of the queue and removes it from the queue. If the queue is empty, the calling thread is blocked until the queue is not empty. Int size() returns the number of current queue elements. Your implementation will be tested by multiple threads simultaneously. Each thread is either a producer thread that calls only enqueue methods, or a consumer thread that calls only dequeue methods. The size method will be called after each test case. Please do not use the built-in limited blocking queue implementation, otherwise the interview will not pass.Copy the code
Input: 1 1 ["BoundedBlockingQueue","enqueue","dequeue" ,"dequeue","enqueue","enqueue","enqueue","enqueue","dequeue"] [[2], [1], [], [], [0], [2], [3], [4], []] output:,0,2,2 [1] : BoundedBlockingQueue queue = new BoundedBlockingQueue(2); // Initialize the queue with capacity = 2. queue.enqueue(1); // The producer thread inserts 1 into the queue. queue.dequeue(); // The consumer thread calls the dequeue and returns 1. queue.dequeue(); // The consumer thread is blocked because the queue is empty. queue.enqueue(0); // The producer thread inserts 0 into the queue. The consumer thread is unblocked and a 0 is ejected from the queue and returned. queue.enqueue(2); // The producer thread inserts 2 into the queue. queue.enqueue(3); // The producer thread inserts 3 into the queue. queue.enqueue(4); // The producer thread is blocked because the queue length has reached the upper limit 2. queue.dequeue(); // The consumer thread pops 2 from the queue and returns. The producer thread unblocks and inserts 4 into the queue. queue.size(); // There are two more elements in the queue. The size() method is called at the end of each set of test cases.Copy the code
Solution:
class BoundedBlockingQueue { int maxLength; LinkedList<Integer> list; ReentrantLock lock; Condition empty; Condition full; public BoundedBlockingQueue(int capacity) { list = new LinkedList(); maxLength = capacity; lock = new ReentrantLock(); empty = lock.newCondition(); full = lock.newCondition(); } public void enqueue(int element) throws InterruptedException { try { lock.lock(); while(list.size()==maxLength){ full.await(); } list.addFirst(element); empty.signal(); } catch (InterruptedException r) { } finally { lock.unlock(); } } public int dequeue() throws InterruptedException { int res = 0; try { lock.lock(); while(list.size()==0){ empty.await(); } res = list.removeLast(); full.signal(); } catch (InterruptedException r) { } finally { lock.unlock(); return res; } } public int size() { return list.size(); }}Copy the code