2 Dec 2013

producer consumer problem in java using (threads) synchronized block (wait() and notify() methods of Object class)

/* producer consumer problem in java using threads, producer consumer problem in java using (threads) synchronized block (wait() and notify() methods of Object class) example code, producer consumer problem in java using multithreading example, producer consumer problem in java using wait and notify */

Producer is the thread which will produce only one item at a time and it will made wait until it is consumed by the consumer.

Consumer is also a thread which will consumes only one item at a time and it is made wait until the Producer produces next item.

No Producer and no Consumer threads will produce and consume two consecutive items respectively.

class Q
{
boolean valset=false;
int n;
synchronized void put(int i)
{
try
{
if(valset)
wait();
else
{
n=i;
System.out.println("put: "+n);
valset=true;
notify();
}//else
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//put()

synchronized int get()
{
try
{
if(!valset)
wait();
else
{
System.out.println("put: "+n);
valset=false;
notify();
}//else
}//try
catch(Exception e)
{
e.printStackTrace();
}
return n;
}
}

 
//Producer class
class Producer implements java.lang.Runnable 
{
Q q;
 java.lang.Thread t1;
int i;
Producer(Q q)
{
this.q=q;
t1=new java.lang.Thread(this,"pt");
t1.start();
}//con
public void run()
{
System.out.println("name of the thread: "+t1.getName());
i=0;
while(true)
q.put(++i);
}//run()
}


 
//Consumer class
class Consumer implements java.lang.Runnable 
{
Q q;
 java.lang.Thread t1;
int i;
Consumer(Q q)
{
this.q=q;
t1=new java.lang.Thread(this,"ct");
t1.start();
}//con
public void run()
{
System.out.println("name of the thread: "+t1.getName());
i=0;
while(true)
i=q.get();
}//run()
}

//main class
public class demo1
{
public static void main(String arg[])
{
Q q=new Q();
Producer pro=new Producer(q);
Consumer con=new Consumer(q);
}
}

how to run:
javac demo1.java
java demo1
note: press ctrl+c to stop

Output:


producer consumer problem in java using (threads) synchronized block

0 comments:

Post a Comment