#493 Producer and Consumer with a Bounded Buffer

Companies:
Digitalleague
Themes:
JavaConcurrencyPractice

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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in