Monday, 22 October 2018

Implement Producer Consumer Pattern using Blocking Queue


  • BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox support of blocking on put() and take().
  • No need of manual empty or full check, Blocking Queue handle it internally.
  • Only put and take operation required
  • Output is like one N produce and then consume like FIFO ordedr
  • Producer.java
    • public class Producer implements Runnable { private static BlockingQueue QUEUE; public Producer(BlockingQueue QUEUE_V) { QUEUE = QUEUE_V; } public void run() { try { int i = 1; while (true) { QUEUE.put(i); System.out.println(i + " Produced"); i++; } } catch (Exception e) { e.printStackTrace(); } } }

  • Consumer.java

    • public class Consumer implements Runnable { private static BlockingQueue QUEUE; public Consumer(BlockingQueue QUEUE_V) { QUEUE = QUEUE_V; } public void run() { consumer(); } private static void consumer() { int item; try { Thread.sleep(1000); while (true) { item = QUEUE.take(); System.out.println(item + " Consumed"); } } catch (Exception e) { e.printStackTrace(); } } }

  • App.java

    • private static BlockingQueue QUEUE = new ArrayBlockingQueue(10); public static void main(String[] args) { Thread producer = new Thread(new Producer(QUEUE)); Thread consumer = new Thread(new Consumer(QUEUE)); producer.start(); consumer.start(); }

  • Output

    • 1 Produced 2 Produced 3 Produced 4 Produced 5 Produced 6 Produced 7 Produced 8 Produced 9 Produced 10 Produced 1 Consumed 11 Produced 2 Consumed 3 Consumed 4 Consumed 5 Consumed 12 Produced 6 Consumed 13 Produced 7 Consumed 14 Produced 8 Consumed 15 Produced 9 Consumed 16 Produced 10 Consumed 17 Produced 11 Consumed 18 Produced

    No comments:

    Post a Comment

    Search This Blog

    Contact us

    Name

    Email *

    Message *