BlockingQueue is a thread-safe queue where we can enqueue on one end of queue, and dequeue on another end of queue.,
All BlockingQueue implementions on array or linked queues are thread-safe implementations.
Below is a simple usage of BlockingQueue.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.Queue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class BlockingQueuesExamples { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<String>(); linkedBlockingQueue.offer("Apple"); linkedBlockingQueue.offer("Orange"); linkedBlockingQueue.offer("Peach"); queueStatus(linkedBlockingQueue); linkedBlockingQueue.offer("Avacado"); queueStatus(linkedBlockingQueue); System.out.println("Dequeued at Head of Queue: " + linkedBlockingQueue.take()); System.out.println("Dequeued at Head of Queue: " + linkedBlockingQueue.take()); queueStatus(linkedBlockingQueue); } public static void queueStatus(Queue linkedBlockingQueue) { System.out.println("---------------------------"); System.out.println("Linked Blocking Queue Size:" + linkedBlockingQueue.size()); System.out.println("Items:"); System.out.println(linkedBlockingQueue); System.out.println("---------------------------"); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
--------------------------- Linked Blocking Queue Size:3 Items: [Apple, Orange, Peach] --------------------------- --------------------------- Linked Blocking Queue Size:4 Items: [Apple, Orange, Peach, Avacado] --------------------------- Dequeued at Head of Queue: Apple Dequeued at Head of Queue: Orange --------------------------- Linked Blocking Queue Size:2 Items: [Peach, Avacado] --------------------------- |