20-CS-4003-001 Organization of Programming Languages Fall 2017
Notify, Wait

Lambda calculus, Type theory, Formal semantics, Program analysis

     Previous     Next           Test5b.java      TestFrame      AuxFrame.java      Sister code     All lectures

Sleep has the same effect as yield (see Test3b.java)

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

class M2 {
   boolean flag;
   TestFrame test;

   public M2 (boolean flag, TestFrame tst) {  this.flag = flag; test = tst;  }
   
   synchronized void saveit (int n) {
      test.text.append("Wait:"+n+"\n"); 
      try { wait(); } catch (Exception e) { }
      test.text.append("Release:"+n+"\n");
   }

   synchronized void doit () {
      test.text.append("Entering doit - notifying processes\n");
      if (flag) notify(); else notifyAll();
      test.text.append("Processes notified\n");
   }
}

class W2 extends Thread {
   JTextField text;
   M2 mp;
   int id;
   
   public W2 (M2 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\n");
   }
}

class Test5Doer extends Thread {
   TestFrame test;
   AuxFrame aux;

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

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

      M2 monitor = new M2(false, test);
      W2 w1 = new W2 (monitor,1,aux.w1t);
      W2 w2 = new W2 (monitor,2,aux.w2t);
      W2 w3 = new W2 (monitor,3,aux.w3t);
      W2 w4 = new W2 (monitor,4,aux.w4t);      
      w1.start();
      w2.start();
      w3.start();
      w4.start();
      test.text.append("Go\n");
      try { 
         sleep(2000);
         test.text.append("Go again\n");
         monitor.doit();
      } catch (Exception e) { }
   }
}

class Test5bFrame extends TestFrame {
   AuxFrame aux;

   public Test5bFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.add(button);
      add("South", p);
      add("Center", new JScrollPane(text));
      aux = new AuxFrame(4);
      aux.setSize(170,170);
      aux.setVisible(true);
   }
   
   public void actionPerformed (ActionEvent evt) {
      (new Test5Doer(this,aux)).start();
   }
}

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