                                                   
class Q {
                                                   
int n;
                                                   
boolean valueSet = false;
                                                          
synchronized int get() {
                                                          
       if(n==0)
                                                   
       try {
                                                  
              wait();
                                                          
       } catch(InterruptedException e) {
                                                          
       System.out.println("InterruptedException caught");
                                                          
       }
                                                   
       System.out.println("Got: " + n);
                     n--;                              
       valueSet = false;
       notify();
       return n;
       }
synchronized void put(int l) {
       if(n==5)
       try {
              wait();
       } catch(InterruptedException e) {
System.out.println("InterruptedException caught");
       }
       this.n ++;

       valueSet = true;
       System.out.println("Put: " + 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) {
if(Math.random()>0.8)
try {
              Thread.sleep(4000);
       } catch(InterruptedException e) {
System.out.println("InterruptedException caught1");
       }
 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) {
if(Math.random()>0.8)
try {
              Thread.sleep(5000);
       } catch(InterruptedException e) {
System.out.println("InterruptedException caught1");
       }
q.get();
}
}
 }
 public class ProdCons {
   public static void main(String args[]) {
Q q = new Q();
 new Producer(q);
 new Consumer(q);
   }
 }


