Blogroll

This blog is created for education about engineering students.All the engineering students are get free downloadable books here. not only books and also different software also available here

9.b. producer_consumer problem in threads


b) 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

Total Pageviews