Skip to content

EX31 - Java Blocking Queue

We try to construct a classical producer-consumer program with Java queues. For this let’s create a program that consists of three parts:

  • a Producer
  • a Consumer
  • a main part, which starts both threads

Question 1 - Producer / Consumer main structure

Write a small Java program that simulation the producer-consumer problem. The program must fulfil the following specifications:

  • The producers will be producing N_ELEMENTS random number from 0 to 100 and will put these numbers in a BlockingQueue. The BlockingQueue has a capacity of QUEUE_BOUND.
  • We’ll have N_PRODUCERS producer threads. They use the put() method to block until there’s free space available in the queue.
  • On the other hand, we have N_CONSUMERS consumer threads that work in a while(true) loop and consume one element that will be printed at the screen. If no element is available, the consumer thread must wait on the take() primitive.

Question 2 - Strategy to stop the consumer thread

The important thing to remember is that we need to stop our consumer threads from waiting for an element to appear in the queue indefinitely. So, what kind of strategy could we use to correctly stop the consumer thread, once the producers finished producing elements?

  1. Describe a possible solution/strategy
  2. Apply your strategy to your code