The difference between a blocking queue and a normal queue is that when the queue is empty, the operation to get elements from the queue is blocked, or when the queue is full, the operation to add elements to the queue is blocked. Threads that attempt to fetch elements from an empty blocking queue are blocked until other threads insert new elements into the empty queue. Similarly, threads that attempt to add new elements to the full blocking queue will also be blocked until other threads have made the queue idle again, such as removing one or more elements from the queue, or completely emptying the queue, showing how to cooperate by blocking the queue:
Thread 1 Adds an element to the blocking queue, while thread 2 removes the element from the blocking queue
Starting with 5.0, the JDK provides the official implementation of the blocking queue in the Java.util.concurrent package. Although the JDK already contains the official implementation of the blocking queue, it is helpful to be familiar with the rationale behind it.
Implementation of the blocking queue
The implementation of a blocking queue is similar to an implementation with an upper bound of semaphore. Here is a simple implementation of the blocking queue
public class Blockingqueue { private List queue = new LinkedList (); private int limit = ten; public blockingqueue (int limit) { this.limit = limit; } Public synchronized void Enqueue (Object item) throws Interruptedexception {while (this.queue.size () = = This.limit) { wait (); } if (this.queue.size () = = 0) { notifyall (); } This.queue.add (item); } Public synchronized Object dequeue () throws interruptedexception{while (this.queue.size () = = 0) { wait (); } if (this.queue.size () = = This.limit) { notifyall (); } Return This.queue.remove (0); } }
It must be noted that the Notifyall method is called only when the size of the queue equals the upper limit (limit) or the lower bound (0) within the Enqueue and Dequeue methods. If the size of the queue is neither equal to the upper bound nor equal to the lower limit, any thread that calls the Enqueue or Dequeue method does not block and can add or remove elements to the queue normally.
Implementation of the Java blocking queue