18. WAJP
that correctly implements Producer-Consumer problem using the concept of Inter
Thread Communication.
Program:
class Producer extends Thread
{
static int i=0;
Consumer obj;
Producer(Consumer obj1)
{
obj=obj1;
}
public void run()
{
System.out.println("producer thread started");
synchronized(obj)
{
while(true)
{
try
{
System.out.println("Value produced is:"+(i+1));
obj.j=++i;
Thread.sleep(10);
wait();
System.out.println("lock is released by producer");
}catch(Exception e)
{
}
}
}
}
}
class Consumer extends Thread
{
int j;
public void run()
{
System.out.println("consumer thread has been started");
synchronized(this)
{
while(true)
{
try
{
System.out.println("value of j before exception"+j);
Thread.sleep(10);
System.out.println("consumed:"+j);
notify();
}catch(Exception e)
{
}
}
}
}
}
class CommDemo
{
public static void main(String[] args)throws Exception
{
Consumer con=new Consumer();
Producer pod=new Producer(con);
con.start();
Thread.sleep(5);
pod.start();
}
}
{
static int i=0;
Consumer obj;
Producer(Consumer obj1)
{
obj=obj1;
}
public void run()
{
System.out.println("producer thread started");
synchronized(obj)
{
while(true)
{
try
{
System.out.println("Value produced is:"+(i+1));
obj.j=++i;
Thread.sleep(10);
wait();
System.out.println("lock is released by producer");
}catch(Exception e)
{
}
}
}
}
}
class Consumer extends Thread
{
int j;
public void run()
{
System.out.println("consumer thread has been started");
synchronized(this)
{
while(true)
{
try
{
System.out.println("value of j before exception"+j);
Thread.sleep(10);
System.out.println("consumed:"+j);
notify();
}catch(Exception e)
{
}
}
}
}
}
class CommDemo
{
public static void main(String[] args)throws Exception
{
Consumer con=new Consumer();
Producer pod=new Producer(con);
con.start();
Thread.sleep(5);
pod.start();
}
}
0 comments:
Post a Comment