Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.

Program Code:
import java.io.*;
class Thread1
{
int n;
boolean valueset=false;
synchronized int get()
{
if (!valueset)
try
{
wait();
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
System.out.println("get" +n);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
valueset=false;
notify();
return n;
}
synchronized int put(int n)
{
if (valueset)
try
{
wait();
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
this.n=n;
valueset=true;
System.out.println("put"+n);
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Excepton occur at : "+e);
}
notify();
return n;
}
}
class Producer implements Runnable
{
Thread1 t;
Producer(Thread1 t)
{
this.t=t;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while (true)
{
t.put(i++);
}
}
}
class Consumer implements Runnable
{
Thread1 t;
Consumer(Thread1 t)
{
this.t=t;
new Thread(this,"Consumer").start();
}
public void run()
{
int i=0;
while (true)
{
t.get();
}
}
}
class ProducerConsumer
{
public static void main(String[] args) throws IOException
{
Thread1 t=new Thread1();
new Producer(t);
new Consumer(t);
System.out.println("Press Control+c to exit");
}
}

Output:
D:\Lab>javac ProducerConsumer.java
D:\Lab>java ProducerConsumer
put0
Press Control+c to exit
get0
put1
get1
put2
get2
put3
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: