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

Lambda calculus, Type theory, Formal semantics, Program analysis

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

Sleep has the same effect as yield (see Test3a.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 Test5aFrame extends TestFrame {
   AuxFrame aux;

   public Test5aFrame () {
      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) {
      text.setText("");
      try { Thread.sleep(200); } catch (Exception e) { }

      M2 monitor = new M2(false, this);
      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();
      text.append("Go\n");
      try { 
         Thread.sleep(2000);
         text.append("Go again\n");
         monitor.doit();
      } catch (Exception e) { }
   }
}

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