20-CS-4003-001 Organization of Programming Languages Fall 2017
Producer/Consumer

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next           Test6a.java      TestFrame      Sister code      Demo     All lectures

Implementing a Consumer-Producer Stream - separate monitor

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class Monitor {
   private int contents; 
   private boolean available = false; // this is the condition variable.

   public synchronized int get() {
      if (available == false) {
         try { wait(); } catch (InterruptedException e) { }
      }
      available = false;
      notify();
      return contents;
   }

   public synchronized void put(int value) {
      if (available == true) {
         try { wait(); } catch (InterruptedException e) { }
      }
      contents = value;
      available = true;
      notify();
   }
}

class Producer extends Thread {
   private Monitor monitor;
   private int number;
   private TestFrame test;

   public Producer(Monitor c, int number, TestFrame tst) {
      monitor = c;
      this.number = number;
      test = tst;
   }

   public void run() {
      for (int i = 0; i < 10; i++) {
         monitor.put(i);
         test.text.append("Producer #" + this.number + " put: " + i+"\n");
      }
   }
}

class Consumer extends Thread {
   private Monitor monitor;
   private int number;
   private TestFrame test;

   public Consumer(Monitor c, int number, TestFrame tst) {
      monitor = c;
      this.number = number;
      test = tst;
   }

   public void run() {
      int value = 0;
      for (int i = 0; i < 10; i++) {
         value = monitor.get();
         test.text.append("Consumer #" + this.number + " got: " + value+"\n");
      }
   }
}

class Test6aFrame extends TestFrame {
   public Test6aFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.add(button);
      add("South",p);
      add("Center", new JScrollPane(text));
   }

   public void actionPerformed (ActionEvent evt) {
      text.setText("");
      try { Thread.sleep(200); } catch (Exception e) { }

      Monitor monitor = new Monitor();
      Producer p1 = new Producer(monitor, 1, this);
      Consumer c1 = new Consumer(monitor, 1, this);
      p1.start();
      c1.start();
   }
}

public class Test6a extends Applet {
   public void init () {
      TestFrame test = new Test6aFrame();
      test.setSize(350,700);
      test.setVisible(true);
   }
}