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_ELEMENTSrandom number from 0 to 100 and will put these numbers in aBlockingQueue. TheBlockingQueuehas a capacity ofQUEUE_BOUND. - We’ll have
N_PRODUCERSproducer threads. They use theput()method to block until there’s free space available in the queue. - On the other hand, we have
N_CONSUMERSconsumer threads that work in awhile(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?
- Describe a possible solution/strategy
- Apply your strategy to your code