BM Balmiki Mandal 06 May 2023 8 views 0 comments Core Java

Solve the Producer-Consumer Problem in Java with Examples

Understanding Producer-Consumer Problem With Example in Java

Understanding Producer-Consumer Problem in Java

Introduction

The Producer-Consumer problem is a classic synchronization problem in computer science. It involves two processes, the producer and the consumer, who share a common, fixed-size buffer as a communication medium. The producer generates data and places it into the buffer, while the consumer retrieves data from the buffer. This scenario raises synchronization issues that need to be addressed to ensure that the producer and consumer operate safely and efficiently.

Key Concepts

1. Producer

  • The producer is responsible for generating data or items that need to be processed.
  • It adds items to the shared buffer.

2. Consumer

  • The consumer consumes or processes the items generated by the producer.
  • It retrieves items from the shared buffer.

3. Shared Buffer

  • The shared buffer is a fixed-size data structure that allows communication between the producer and the consumer.
  • It acts as a queue where items are added by the producer and retrieved by the consumer.

Problem Statement

Design a Java program to illustrate the Producer-Consumer problem using multi-threading.

Example

java

import java.util.LinkedList;

class SharedBuffer {
    private LinkedList<Integer> buffer = new LinkedList<>();
    private final int MAX_SIZE = 5;

    public synchronized void produce(int item) throws InterruptedException {
        while (buffer.size() == MAX_SIZE) {
            wait();
        }

        buffer.add(item);
        notifyAll();
    }

    public synchronized int consume() throws InterruptedException {
        while (buffer.size() == 0) {
            wait();
        }

        int item = buffer.removeFirst();
        notifyAll();
        return item;
    }
}

class Producer implements Runnable {
    private SharedBuffer buffer;

    public Producer(SharedBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                buffer.produce(i);
                System.out.println("Produced: " + i);
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Consumer implements Runnable {
    private SharedBuffer buffer;

    public Consumer(SharedBuffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 5; i++) {
                int item = buffer.consume();
                System.out.println("Consumed: " + item);
                Thread.sleep(1500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SharedBuffer buffer = new SharedBuffer();

        Thread producerThread = new Thread(new Producer(buffer));
        Thread consumerThread = new Thread(new Consumer(buffer));

        producerThread.start();
        consumerThread.start();
    }
}

 

Explanation

  • We create a shared buffer using a synchronized class in Java.
  • The produce and consume methods ensure that producers and consumers wait when the buffer is full or empty, respectively.
  • The notifyAll method is used to notify waiting threads when a change in the buffer occurs.
  • We create a producer and a consumer thread that operate on the same buffer.

Conclusion

The Producer-Consumer problem is a fundamental synchronization problem in concurrent programming. Understanding and effectively implementing solutions to this problem is crucial for designing efficient multi-threaded applications.

Enroll Now:

[Course in Production] "Start Supercharging Your Productivity!"

Contact Us:

  • For any inquiries, please email us at [info@electro4u.net].
  • Follow us on [Social Media Links] for updates and tips.

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023