Home » Java programs

Producer and Consumer Code in Java

In this article, we will be looking at consumer and producer problem in Java and we would be writing a java code to implement the consumer and producer concept in java.
Submitted by Raunak Goswami, on October 08, 2018

This also helps us to understand the concept of synchronised multi-threading in java, the basic work of our code is that the producer will produce a thread and load it into the memory and after producing the producer thread we would be loading the consumer thread to produce a consumable thread which will consume the value of the produce thread.

We would basically be creating two classes named as producer and consumer class.

The producer class will be running a producer thread which is defined as the put method and after running of producer thread we will use consumer class to run the consumer thread which is basically the get method.

Below is the java code written for the same

package cp;

class value
{
	int n;
	int value=0;
	synchronized int get()
	{
		if(value==0)
		try
		{
			wait(1000);
		}
		catch(InterruptedException e)
		{
			System.out.println("Exception caught");
		}
		System.out.println("consumed the value:"+n);
		value=0;
		notify();
		return n;
	}
	synchronized void put(int n)
	{
		if(value==1)
		try
		{
			wait(1000);
		}
		catch(InterruptedException e)
		{
			System.out.println("exception");
		}
		this.n=n;
		value=1;
		System.out.println("produced:"+n);
		notify();
	}
}
class Produce implements Runnable
{
	value first;
	Produce(value first)
	{
		this.first=first; 
		new Thread(this,"Produce").start();
	}
	public void run()
	{
		int i=0;
		while(i<10)
		{
			first.put(i++);
		}
	}
}
class Consume implements Runnable
{
	value second;
	Consume(value second)
	{
		this.second=second ;
		new Thread(this,"Consum").start();
	}
	public void run()
	{
		int i=0;
		while(i<10)
		{
			second.get();
			i++;
		}
	} 
}
public class Produceconsume
{
	public static void main(String[] args)
	{
		value first=new value();
		new Produce(first);
		new Consume(first);
	}
}

Output

produced:0
consumed the value:0
produced:1
consumed the value:1
produced:2
consumed the value:2
produced:3
consumed the value:3
produced:4
consumed the value:4
produced:5
consumed the value:5
produced:6
consumed the value:6
produced:7
consumed the value:7
produced:8
consumed the value:8
produced:9
consumed the value:9

we have used a while loop here to create 10 producer threads and their respective consumer threads. Hope you have understood the basic concept of producer and consumer threads, there are numerous codes available for producer and consumer threads online, once you develop the understanding you can write your own code too. Have a great day ahead and happy learning.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.