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

Latest

programs

Monday, October 10, 2011

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


Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.
class Q
{
boolean valueSet=false;
int n;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Exception is:"+e);
}
System.out.println("got:"+n);
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println
("\n Exception in put:"+e);
}
this.n=n;
valueSet=true;
System.out.println("\nput:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
q.put(i++);
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
q.get();
}
}
class ProdConsDemo
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("\n press ctrl+c to stop");
}
}

No comments:

Post a Comment