Pages

using synchronized keyword

//using synchronized keyword
class Common
{
int i;
boolean flag=true;
/* If flag is true, Producer will get executed and makes consumer to be in waiting state. After Completion, producer makes Consumer Thread to get executed by making flag as false. Stated simply,if flag is true, Consumer will wait and producer will wait if flag is false.*/
synchronized void produce(int j)
{
 if(flag)
 {
 i=j;
System.out.println("Produced Item =  "+ i);
flag=false;
notify();//making Consumer to get Executed
}
try{
wait();}catch(Exception e)
{ System.out.println(e);}
}
synchronized int consume()
{
try{
 if(flag)
wait();
}catch(Exception e)
{
System.out.println(e);
}
 flag=true;
 notify();
 return i;
}
}
class Producer extends Thread
{
 Common c1;
 Producer(Common c1)
 { this.c1=c1; }
 public void run()
 {
 int i=0;
 while(true)
 {
 i++;
 c1.produce(i);
 try{sleep(1000);}catch(Exception e)
 {System.out.println(e);}
}
}
}
class Consumer extends Thread
{
 Common c1;
 Consumer(Common c1)
 { this.c1=c1; }
 public void run()
 {
 while(true)
 {
 int j=c1.consume();
 System.out.println("Consumed item= " + j);
 try{sleep(1000);}catch(Exception e)
 {System.out.println(e);}
}
}
}
class SynDemo2
{
public static void main(String args[])
{
 Common c1=new Common();
 Producer p=new Producer(c1);
 Consumer c=new Consumer(c1);
 p.start();
 c.start();
}

}