#493 Producer and Consumer with a Bounded Buffer
There are two threads: a producer and a consumer. The producer generates some data, for example numbers. The consumer consumes it.
The two threads share a common data buffer whose size is limited.
If the buffer is empty, the consumer must wait until data appears.
If the buffer is full, the producer must wait until the consumer takes data and frees space.
Implement the run and produce methods:
public class Main {
public static void main(String... args) {
LinkedList<Double> sharedQueue = new LinkedList<>();
int size = 4;
Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");
Thread consThread = new Thread(new Consumer(sharedQueue), "Consumer");
prodThread.start();
consThread.start();
}
}
class Producer implements Runnable {
// Shared queue
private final Queue<Double> sharedQueue;
// Maximum size
private final int SIZE;
// Constructor
public Producer(Queue<Double> sharedQueue, int size) {
this.sharedQueue = sharedQueue;
this.SIZE = size;
}
@Override
public void run() {
throw new UnsupportedOperationException("Implemented it!");
}
private double produce() throws InterruptedException {
throw new UnsupportedOperationException("Implemented it!");
}
}
class Consumer implements Runnable {
// Shared queue
private final Queue<Double> sharedQueue;
public Consumer(Queue<Double> sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
throw new UnsupportedOperationException("Implemented it!");
}
private Double consume() throws InterruptedException {
throw new UnsupportedOperationException("Implemented it!");
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor