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

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next           Test9b.java      TestFrame      Sister code     All lectures

Threads Can Be Tricky!

Example showing how tricky Threads can be. Printing is directed to standard out as well as a JTextArea but in the sister applet (Test9a.java) nothing appears in the JTextArea. In this applet printing to the JTextArea works great. The difference is the control portion of the code is Threaded in this applet but not in the sister applet.
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class M4 {
   TestFrame test;

   public M4 (TestFrame tst) {  test = tst; }

   synchronized void doit () {
      test.text.append("Entering doit - notifying processes\n");
      notifyAll();
      test.text.append("Processes notified\n");
      try { test.text.append("Doit waiting\n"); wait(); } 
      catch (Exception e) { }
   }
   
   synchronized void saveit (int n) {
      try { test.text.append("Wait:"+n+"\n"); wait(); } 
      catch (Exception e) { }
      test.text.append("Release:"+n+"\n");
   }
}

class W4 extends Thread {
   JTextField text;
   M4 mp;
   int id;
   
   public W4 (M4 p, int n, JTextField t) { mp = p; id = n; text = t; }

   public void run () {
      mp.test.text.append("Starting "+id+"\n");
      mp.saveit(id);
      for (long i=0 ; i < 10000000 ; i++) 
	 if ((i%10000) == 0) text.setText(String.valueOf(i));
      mp.test.text.append("Terminating "+id+"\n");
   }
}

// Control portion is threaded
class Test9Doer extends Thread {
   TestFrame test;
   AuxFrame aux;

   public Test9Doer (TestFrame tst, AuxFrame ax) { test = tst; aux = ax; }

   public void run () {
      test.text.setText("");
      try { sleep(200); } catch (Exception e) { }

      M4 m = new M4(test);
      W4 w1 = new W4(m,1,aux.w1t);
      W4 w2 = new W4(m,2,aux.w2t);
      W4 w3 = new W4(m,3,aux.w3t);
      W4 w4 = new W4(m,4,aux.w4t);  
      w1.start();
      w2.start();
      w3.start();
      w4.start();

      test.text.append("Go\n");
      try { sleep(2000); } catch (Exception e) { }
      test.text.append("Go again\n");

      m.doit();
   }
}

class Test9bFrame extends TestFrame implements ActionListener {
   AuxFrame aux;

   public Test9bFrame () {
      setLayout(new BorderLayout());
      add("Center", new JScrollPane(text));
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(button);
      add("South", p);
      aux = new AuxFrame(4);
      aux.setSize(170,170);
      aux.setVisible(true);
   }

   public void actionPerformed (ActionEvent evt) { 
      (new Test9Doer(this,aux)).start(); 
   }
}

public class Test9b extends Applet {
   public void init () {
      TestFrame test = new Test9bFrame();
      test.setSize(320,700);
      test.setVisible(true);
   }
}