The following is transferred from http://ifeve.com/blocking-queues/:
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 classBlockingqueue {PrivateList queue =NewLinkedList (); Private intLimit = 10; PublicBlockingqueue (intlimit) { This. Limit =limit; } Public synchronized voidEnqueue (Object Item)throwsinterruptedexception { while( This. queue.size () = = This. Limit) {Wait (); } if( This. queue.size () = = 0) {notifyall (); } This. Queue.add (item); } Public synchronizedObject dequeue ()throwsinterruptedexception{ 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.
25. Java concurrency and multithreading-blocking queues