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

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next          Test1a.java      TestFrame      Sister code     All lectures

Simple test of notify, notifyAll, wait, synchronize

Simple test of notify, notifyAll, wait, synchronize. The Monitor allows W1 objects to wait (via method 'a') until awakened by an N1 object (via method 'b'). Control portion of code is not Threaded.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

// A Monitor for W (for waiting) objects
class M1 {
   boolean flag;
   TestFrame test;

   public M1 (boolean flag, TestFrame tst) {  this.flag = flag; test = tst; }

   synchronized public void a () {
      test.text.append("a: wait ("+((W1)Thread.currentThread()).numb+")\n");
      try { wait(); } catch (Exception e) {}
      test.text.append("a: rise ("+((W1)Thread.currentThread()).numb+")\n");
   }

   synchronized public void b () {
      test.text.append("b: notify ("+((N1)Thread.currentThread()).numb+")\n");
      if (flag) notify(); else notifyAll();
      test.text.append("b: done ("+((N1)Thread.currentThread()).numb+")\n");
   }
}

class N1 extends Thread {
   M1 monitor;
   int numb;

   public N1 (int n, M1 mn) {  monitor = mn;  numb = n;  }

   public void run () {
      test.text.append("N1: Starting ("+numb+")\n");
      monitor.b();
      test.text.append("N1: Finishing ("+numb+")\n");
   }
}

class W1 extends Thread {
   M1 monitor;
   int numb;

   public W1 (int n, M1 mn) {  monitor = mn;  numb = n;  }

   public void run () {
      test.text.append("W1: Starting ("+numb+")\n");
      monitor.a();
      test.text.append("W1: Finishing ("+numb+")\n");
   }
}

class Test1aFrame extends TestFrame {
   public Test1aFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(1,2));
      p.add(choice);
      choice.addItem("notify");
      choice.addItem("notifyAll");
      p.add(button);
      add("South",p);
      add("Center", new JScrollPane(text));
   }
	
   public void actionPerformed (ActionEvent evt) {
      boolean flag;
      text.setText("");
      try { Thread.sleep(200); } catch (Exception e) { }
      
      try {
	 if (choice.getSelectedItem().equals("notifyAll")) {
	    flag = false;
	    text.append("\nnotifyAll() -\n");
	 } else {
	    flag = true;
	    text.append("\nnotify() -\n");				
	 }
	 
	 M1 monitor = new M1 (flag, this);
	 W1 w1 = new W1 (1, monitor);
	 W1 w2 = new W1 (2, monitor);
	 W1 w3 = new W1 (3, monitor);
	 N1 n1 = new N1 (99, monitor);
	 w1.start();
	 w2.start();
	 w3.start();
	 n1.start();
      } catch (Exception e) { }
   }
}

public class Test1a extends Applet {
   public void init () {
      TestFrame test = new Test1aFrame();
      test.setSize(300,600);
      test.setVisible(true);
   }
}