Producer Consumer Explanation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

GeeksforGeeks Custom Search


A computer science portal for geeks
Practice GATE CS Placements Videos Contribute
Login/Register

Quick Links
for Java

Recent
Articles

MCQ /
Quizzes

Java
Collections

Practice
Problems

Commonly
Asked
Questions Set
1 & Set 2

Basics

Identifiers, Data
types & Variables

Scope of
Variables

Operators

Loops and
Decision Making

Explore More...

Input / Output

Ways to read
Input from
Console

1 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

Scanner VS
BufferReader
Class

Formatted output

Fast I/O in Java in


Competitive
Programming

Command Line
arguments

Explore More...

Arrays

Arrays in Java

Default array
values in Java

Compare two
arrays

Final Arrays &


Jagged Arrays

Array
IndexOutofbounds
Exception

Explore More...

Strings

String Class in
Java

StringBuffer ,
StringTokenizer &
StringJoiner

Initialize and
Compare Strings

String vs
StringBuilder vs
StringBuffer

Integer to String &


String to Integer

Search, Reverse
and Split()

Explore More...

2 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

OOP in Java

Classes and
Objects in Java

Different ways to
create objects

Access Modifiers
in Java

Object class in
Java

Encapsulation &
Inheritance

Method
Overloading &
Overriding

Explore More...

Constructors

Constructors &
Constructor
Chaining

Constructor
Overloading

Private
Constructors and
Singleton Classes

Explore More...

Methods

Parameter
Passing

Returning Multiple
Values

Private and Final


Methods

Default Methods

Explore More...

Exception
Handling

Exceptions &
Types of

3 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

Exceptions

Flow control in try-


catch & Multicatch

throw and throws

Explore More...

Multithreading

Multithreading

Lifecycle and
States of a
Thread

Main Thread

Synchronization

Inter-thread
Communication &
Java Concurrency

Explore More...

File Handling

File Class

File Permissions

Different ways of
Reading a text file

Delete a File

Explore more...

Garbage
Collection

Garbage
Collection

Mark and Sweep

Explore more...

Java Packages

Packages

Java.io Package

4 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

Java.lang
package

Java.util Package

Networking

Socket
Programming

URL class in Java

Reading from a
URL

Inet Address
Class

A Group Chat
Application

Explore more...

Producer-Consumer solution using threads in


Java
In computing, the producerconsumer problem (also known as the bounded- 3.5
buffer problem) is a classic example of a multi-process synchronization prob-
lem. The problem describes two processes, the producer and the consumer, which
share a common, fixed-size buffer used as a queue.

The producers job is to generate data, put it into the buffer, and start again.
At the same time, the consumer is consuming the data (i.e. removing it from the
buffer), one piece at a time.

Problem
To make sure that the producer wont try to add data into the buffer if its full and that
the consumer wont try to remove data from an empty buffer.

Solution
The producer is to either go to sleep or discard data if the buffer is full. The next time
the consumer removes an item from the buffer, it notifies the producer, who starts to
fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer
to be empty. The next time the producer puts data into the buffer, it wakes upthe
sleeping consumer.
An inadequate solution could result in a deadlock where both processes are waiting

5 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

to be awakened.

Recommended Reading- Multithreading in JAVA, Synchronized in JAVA , Inter-


thread Communication

Implementation of Producer Consumer Class

A LinkedList list to store list of jobs in queue.


A Variable Capacity to check for if the list is full or not
A mechanism to control the insertion and extraction from this list so that we do
not insert into list if it is full or remove from it if it is empty.

Note: It is recommended to test the below program on a offline IDE as infinite loops
and sleep method may lead to it time out on any online IDE

// Java program to implement solution of producer


// consumer problem.
import java.util.LinkedList;

public class Threadexample


{
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread


Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)

6 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumber (removes items).
public static class PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();

System.out.println("Producer produced-"
+ value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();

7 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

//to retrive the ifrst job in the list


int val = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}
}
}
}

Run on IDE

Output:

Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2

Important Points

In PC class (A class that has both produce and consume methods), a linked list
of jobs and a capacity of the list is added to check that producer does not pro-
duce if the list is full.
In Producer class, the value is initialized as 0.
Also, we have an infinite outer loop to insert values in the list. Inside this
loop, we have a synchronized block so that only a producer or a consumer
thread runs at a time.
An inner loop is there before adding the jobs to list that checks if the job list
is full, the producer thread gives up the intrinsic lock on PC and goes on
the waiting state.
If the list is empty, the control passes to below the loop and it adds a value
in the list.
In the Consumer class, we again have an infinite loop to extract a value from
the list.
Inside, we also have an inner loop which checks if the list is empty.
If it is empty then we make the consumer thread give up the lock onPC
and passes the control to producer thread for producing more jobs.
If the list is not empty, we go round the loop and removes an item from the

8 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

list.
In both the methods, we use notify at the end of all statements. The reason is
simple, once you have something in list, you can have the consumer thread con-
sume it, or if you have consumed something, you can have the producer pro-
duce something.
sleep() at the end of both methods just make the output of program run in step
wise manner and not display everything all at once so that you can see what ac-
tually is happening in the program.

Exercise :

Readers are advised to use if condition in place of inner loop for checking
boundary conditions.
Try to make your program produce one item and immediately after that the con-
sumer consumes it before any other item is produced by the consumer.

Reference https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would
like to contribute, you can also write an article using contribute.geeksforgeeks.org or
mail your article to [email protected]. See your article appearing on the
GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more infor-
mation about the topic discussed above.

GATE CS Corner Company Wise Coding Practice

Java Login to Improve this Article

Please write to us at [email protected] to report any issue with the above content.

Recommended Posts:

CountDownLatch in Java
Thread Pools in Java
Inter-thread Communication in Java
Multithreading in Java
Semaphore in Java

9 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

Java 8 Predicate with Examples


Java.util.TreeMap.floorEntry() and floorKey() in Java
Java.util.TreeMap.put() and putAll() in Java
Comparing enum members in Java
Fail Fast and Fail Safe Iterators in Java

(Login to Rate)

Average Difficulty : 3.5/5.0


3.5 Based on 23 vote(s)
Add to TODO List
Mark as DONE
Basic Easy Medium Hard Expert

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the
link here.

Share this post!

10 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

12 Comments GeeksforGeeks
1 Login

Sort by Newest
Recommend Share

Join the discussion

LOG IN WITH OR SIGN UP WITH DISQUS ?

Name

Amogha R 15 days ago


Another easy example:
package Threads;

class Controller {
String dataItem = "A";
volatile int count = 50;

synchronized public void consume() {

while (count > 0) {


count--;
try {

wait();
// Consume dataItem
System.out.println("Consumed:" + dataItem);
Thread.sleep(2000);
notify();

} catch (InterruptedException e) {
see more

Reply Share

Alexey Smirnov 20 days ago


Corrections:
In Producer class, the value is initialized as 0...
In the Consumer class, we again have an infinite loop to extract a value from the
list...

not class, but methods

any other item is produced by the consumer.


by producer!
Reply Share

11 of 12 11/28/17, 3:40 AM
Producer-Consumer solution using threads in Ja... http://www.geeksforgeeks.org/producer-consum...

@geeksforgeeks, Some rights reserved Contact Us! About Us! Careers!


Privacy Policy

12 of 12 11/28/17, 3:40 AM

You might also like