Write a Java program that correctly implements the producer - consumer problem using the concept of inter-thread communication. (use of synchronize)
Write a Java program that correctly implements the producer - consumer problem
using the concept of inter-thread communication. (use of synchronize)
Write a Java program that correctly implements the producer - consumer problem using the concept of inter-thread communication. (use of synchronize)
- import java.util.LinkedList;
- public class Main {
- public static void main(String[] args) {
- // Create a shared buffer
- LinkedList<Integer> buffer = new LinkedList<>();
- int capacity = 5;
- // Create the producer and consumer threads
- Thread producer = new Thread(new Producer(buffer, capacity));
- Thread consumer = new Thread(new Consumer(buffer, capacity));
- // Start the threads
- producer.start();
- consumer.start();
- }
- }
- // The producer thread that adds items to the buffer
- class Producer implements Runnable {
- private LinkedList<Integer> buffer;
- private int capacity;
- public Producer(LinkedList<Integer> buffer, int capacity) {
- this.buffer = buffer;
- this.capacity = capacity;
- }
- public void run() {
- for (int i = 1; i <= 10; i++) {
- synchronized (buffer) {
- while (buffer.size() == capacity) {
- try {
- System.out.println("Buffer is full. Producer waiting...");
- buffer.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- buffer.add(i);
- System.out.println("Produced: " + i);
- buffer.notifyAll();
- }
- }
- }
- }
- // The consumer thread that removes items from the buffer
- class Consumer implements Runnable {
- private LinkedList<Integer> buffer;
- private int capacity;
- public Consumer(LinkedList<Integer> buffer, int capacity) {
- this.buffer = buffer;
- this.capacity = capacity;
- }
- public void run() {
- while (true) {
- synchronized (buffer) {
- while (buffer.isEmpty()) {
- try {
- System.out.println("Buffer is empty. Consumer waiting...");
- buffer.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- int item = buffer.remove();
- System.out.println("Consumed: " + item);
- buffer.notifyAll();
- }
- }
- }
- }
Givan by -Ujjwal Matoliya