Producer-consumer problem

Report a typo

In the producer-consumer problem, there is one producer that is producing something and there is a consumer that is consuming the products produced by the producer. The producer and consumer share the same memory buffer that is of fixed size.

The producer's job is to generate the data, put it into the buffer, and again start generating data, while the consumer's job is to consume the data from the buffer.

Your task is to ensure that the producer won't try to add data to the buffer if it's full and that the consumer won't try to remove data from an empty buffer. To that end, you will implement the class Buffer, which represents the buffer you are trying to synchronize. The size of the Buffer class in this problem will be limited to 1.

There are also two threads called Consumer and Producer.

Producer will generate data and try to put it in the Buffer by calling its put() method.

Consumer will consume the data stored in Buffer by calling its get() method.

Sample Input 1:

123

Sample Output 1:

Producer produced data : 1
Consumer consumed data : 1
Producer produced data : 2
Consumer consumed data : 2
Producer produced data : 3
Consumer consumed data : 3
Write a program in Java 17
import java.util.concurrent.Semaphore;

class Buffer {
// the data stored in Buffer. Do not change or remove this line.
private char data;
//init your attributes here

// to get data from Buffer
public void get() throws InterruptedException {
//complete this method

// consumer consuming data, do not change or remove this line
System.out.println("Consumer consumed data : " + data);
}

// to put data in buffer
public void put(char data) throws InterruptedException {
//complete this method

// producer producing an data, do not change or remove this lines
this.data = data;
System.out.println("Producer produced data : " + data);
}
}
___

Create a free account to access the full topic