1.

What is BlockingQueue?

Answer»

BlockingQueue basically represents a queue that is thread-safe. Producer thread inserts resource/element into the queue using put() method unless it gets full and consumer thread takes resources from the queue using take() method until it gets empty. But if a thread tries to dequeue from an empty queue, then a PARTICULAR thread will be blocked until some other thread inserts an item into the queue, or if a thread tries to insert an item into a queue that is already full, then a particular thread will be blocked until some threads take away an item from the queue. 

Example

package org.arpit.java2blog; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; PUBLIC class BlockingQueuePCExample { public static void main(String[] args) { BlockingQueue<String> queue=NEW ArrayBlockingQueue<>(5); Producer producer=new Producer(queue); Consumer consumer=new Consumer(queue); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } static class Producer implements Runnable { BlockingQueue<String> queue=null; public Producer(BlockingQueue queue) { super(); this.queue = queue; } @OVERRIDE public void run() { try { System.out.println("Producing element 1"); queue.put("Element 1"); Thread.sleep(1000); System.out.println("Producing element 2"); queue.put("Element 2"); Thread.sleep(1000); System.out.println("Producing element 3"); queue.put("Element 3"); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Consumer implements Runnable { BlockingQueue<String> queue=null; public Consumer(BlockingQueue queue) { super(); this.queue = queue; } @Override public void run() { while(true) { try { System.out.println("Consumed "+queue.take()); } catch (InterruptedException e) { e.printStackTrace(); } } } } }

Output

Producing element 1 Consumed Element 1 Producing element 2 Consumed Element 2 Producing element 3 Consumed Element 3


Discussion

No Comment Found