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

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next           Test7a.java      TestFrame      Sister code     All lectures

Abstract Stream class subclassed by producers

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

abstract class Stream extends Thread {
   TestFrame test;
   int value;
   
   synchronized public void putIt (int t) {
      value = t;
      notify();

      if (test != null)
         test.out.append("PutIt ("+value+"): "+Thread.currentThread()+"\n");

      try { wait(); } catch (Exception e) {  }
   }

   synchronized public int next () {
      if (this.getState() == Thread.State.NEW) start(); else notify();

      try { wait(); } catch (Exception e) {  }

      return value;
   }
}

class Successor extends Stream {
   int number = 0;

   public Successor (TestFrame test) { this.test = test; }

   public void run () {  while (true) { putIt(number++); } }
}

class Times extends Stream {
   Stream stream;

   Times (Stream s, TestFrame test) { stream = s;  this.test = test; }

   public void run () { while (true) { putIt(stream.next()*3); } }
}

class Test7aFrame extends TestFrame {
   Stream stream = null;

   public Test7aFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(button);
      button.setText("Connect");
      p.add(next);
      add("South",p);
      p = new JPanel();
      p.setLayout(new GridLayout(2,1));
      p.add(new JScrollPane(text));
      p.add(new JScrollPane(out));
      add("Center",p);
   }

   public void actionPerformed (ActionEvent evt) {
      if (evt.getSource() == button) {
         text.setText("");
         stream = new Times(new Successor(this),this);
         text.append("Stream connection opened\n");
         stream.next();
      } else if (stream == null) {
         out.append("You must connect first - press start\n");
      } else {
         text.append("Next token:  "+stream.next()+"\n");
      }
   }
}

public class Test7a extends Applet {
   public void init () {
      TestFrame test = new Test7aFrame();
      test.setSize(700,600);
      test.setVisible(true);
   }
}