Java Threads - Producer consumer problem

// Thread Synchronization
// Producer Consumer Problem

class Q
{
     int n;
     boolean Flag = false;

     synchronized int get()
     {
          if(Flag == false)
          try
          {
              wait();
          }
          catch(InterruptedException e)
          {
              System.out.println("InterruptedException caught");
          }
         
          System.out.println("Received : "+n);
          Flag = false;
          notify();
          return n;
     }  

     synchronized void put(int n)
     {
          if(Flag == true)
          try
          {
              wait();
          }
          catch(InterruptedException e)
          {
              System.out.println("InterruptedException caught");
          }
         
          this.n = n;
          Flag = true;
          System.out.println("Sent : "+n);
          notify();
     }  
}

class Producer implements Runnable
{
     Q q;
     Thread t;
    
     Producer(String name, Q q)
     {
          this.q = q;
          t = new Thread(this, name);
          t.start();
     }

     public void run()
     {
          int i=1;
         
          while(true)
              q.put(i++);
     }
}


class Consumer extends Thread
{
     Q q;
    
     Consumer(String name, Q q)
     {
          super(name);
          this.start();
          this.q = q;
     }

     public void run()
     {
          while(true)
              q.get();
     }
}

class PC
{
     public static void main(String as[])
     {
          Q q1 = new Q();
          Producer p1 = new Producer("P", q1);
          Consumer c1 = new Consumer("C", q1);
     }
}

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu