Consumer Producer Problem in Java using Queue and get put methods

gautamsh5704 16 views 12 slides Oct 19, 2024
Slide 1
Slide 1 of 12
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12

About This Presentation

A presentation on consumer producer problem


Slide Content

Consumer-Producer Problem By Gautam Sharma

In computer science, a consumer-producer problem is a synchronization problem in which two or more processes share a common resource. One process, the producer, generates data and puts it into the shared resource. The other process, the consumer, consumes the data from the shared resource. The challenge is to ensure that the producer does not produce data faster than the consumer can consume it, and that the consumer does not consume data that has not yet been produced. This can be a challenging problem to solve, especially in multi-threaded environments. INTRODUCTION

Things to Consider The producer should produce data only when the buffer is not full. In case it is found that the buffer is full, the producer is not allowed to store any data into the memory buffer Data can only be consumed by the consumer if and only if the memory buffer is not empty. In case it is found that the buffer is empty, the consumer is not allowed to use any data from the memory buffer. Accessing memory buffer should not be allowed to producer and consumer at the same time.

Source Code

Container class Queue { private LinkedList<Integer> list = new LinkedList<>(); private int capacity; public Queue(int capacity) { this.capacity = capacity; }

Put Method public synchronized void put(int value) throws InterruptedException { while (list.size() == capacity) wait(); list.add(value); System.out.println("Producer has produced: " + value); notify(); }

Get Method public synchronized int get() throws InterruptedException { while (list.size() == 0) { wait(); } int value = list.removeFirst(); System.out.println("Consumer has consumed: " + value); notify(); return value; } }

Producer Class class Producer extends Thread { private Queue queue; public Producer(Queue queue) { this.queue = queue; } public void run() { try { for (int i = 0; i < queue.capacity; i++) { queue.put(i + 1); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace();} }

Consumer Class class Consumer extends Thread { private Queue queue; public Consumer(Queue queue) {this.queue = queue;} public void run() { try { for (int i = 0; i < 5; i++) { queue.get() ; Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } }

Main Class public class Main { public static void main(String[] args) { Queue queue = new Queue(5); Producer producer = new Producer(queue); Consumer consumer = new Consumer(queue); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); }

THANK YOU Do you have any questions?
Tags