JAVA WEEK9(B)
/* Week 9 : b) Write a Java program that correctly implements producer consumer
problem using the concept of inter thread communication. */



class LabPro17
{
        int n;
        boolean vs = false;
        synchronized int get()
        {
           if(!vs)
           try{wait();}
           catch(InterruptedException e)
           { System.out.println("InterruptedException caught");}
           System.out.println("got:" + n);
           vs = false;
                      notify();
          return n;
        }
        synchronized int put(int n)
        {
           if(vs)
           try{wait();}
           catch(InterruptedException e)
           { System.out.println("InterruptedException caught");}
           this.n = n;
           vs = true;
                      System.out.println("put:" + n);
                      notify();
          return n;
        }
}
class Producer implements Runnable
{
        LabPro17 k;
        Producer(LabPro17 k)
        {
           this.k = k;
           new Thread(this, "Producer").start();
        }
        public void run()
        {
          int i = 0;
          while(true)
        {k.put(i++);}
        }
}
class Consumer implements Runnable
{
        LabPro17 k;
        Consumer(LabPro17 k)
        {
           this.k = k;
           new Thread(this, "Consumer").start();
        }
        public void run()
        {
           while(true)
        {k.get();}
        }
}
class PCFixed
                                       Page 1
JAVA WEEK9(B)
{
 public static void main(String args[])
    {
        LabPro17 k = new LabPro17();
        new Producer(k);
        new Consumer(k);
        System.out.println("press control - c to stop. ");
      }
}




                                       Page 2

Java Week9(B) Notepad

  • 1.
    JAVA WEEK9(B) /* Week9 : b) Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. */ class LabPro17 { int n; boolean vs = false; synchronized int get() { if(!vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} System.out.println("got:" + n); vs = false; notify(); return n; } synchronized int put(int n) { if(vs) try{wait();} catch(InterruptedException e) { System.out.println("InterruptedException caught");} this.n = n; vs = true; System.out.println("put:" + n); notify(); return n; } } class Producer implements Runnable { LabPro17 k; Producer(LabPro17 k) { this.k = k; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) {k.put(i++);} } } class Consumer implements Runnable { LabPro17 k; Consumer(LabPro17 k) { this.k = k; new Thread(this, "Consumer").start(); } public void run() { while(true) {k.get();} } } class PCFixed Page 1
  • 2.
    JAVA WEEK9(B) { publicstatic void main(String args[]) { LabPro17 k = new LabPro17(); new Producer(k); new Consumer(k); System.out.println("press control - c to stop. "); } } Page 2