Explain Java BlockingQueue with Producer-Consumer thread example

(Last Updated On: April 9, 2017)

Java BlockingQueue interface is used to implement producer consumer design pattern. This design pattern comes to solve common problem, in which producer and consumer threads use the same queue to pass over the information.

In the Blocking Queue, producer will put elements and wait till space is available if queue is full and consumer will fetch elements and wait till element is available if queue is empty.
Producer Thread produces data and Consumer thread consumes it in FIFO order as blocking queue allows elements to be accessed in FIFO.

blocking-queue

 

Example:

Blocking Queue Sample:

Producer:

Consumer:

Output:
Producer Producing :data1
Producer Producing :data2
Producer Producing :data3
Producer Producing :data4
Producer Producing :data5
Producer Producing :data6
Consumer Consuming :data1
Producer Producing :data7
Consumer Consuming :data2
Producer Producing :data8
Consumer Consuming :data3
Producer Producing :data9
Consumer Consuming :data4
Consumer Consuming :data5
Producer Producing :data10
Consumer Consuming :data6
Producer Producing :data11
Consumer Consuming :data7
Producer Producing :data12
Consumer Consuming :data8
Producer Producing :data13
Consumer Consuming :data9
Producer Producing :data14
Consumer Consuming :data10
Producer Producing :data15
Consumer Consuming :data11
Producer Producing :data16
Consumer Consuming :data12
Producer Producing :data17
Consumer Consuming :data13
Producer Producing :data18
Consumer Consuming :data14
Producer Producing :data19
Consumer Consuming :data15
Producer Producing :data20
Consumer Consuming :data16
Consumer Consuming :data17
Consumer Consuming :data18
Consumer Consuming :data19
Consumer Consuming :data20