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

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next          Test2a.java      TestFrame      Sister code     All lectures

Notify wakes up waiting threads in the same monitor

Notify affects threads waiting in same monitor
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 () {
      monitor.test.text.append("N1: Starting ("+numb+")\n");
      monitor.b();
      monitor.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 () {
      monitor.test.text.append("W1: Starting ("+numb+")\n");
      monitor.a();
      monitor.test.text.append("W1: Finishing ("+numb+")\n");
   }
}

class Test2aFrame extends TestFrame {
   public Test2aFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.add(button);
      add("South",p);
      add("Center", new JScrollPane(text));
   }
	
   // Two different monitors take different W objects
   public void actionPerformed (ActionEvent evt) {
      text.setText("");
      try { Thread.sleep(200); } catch (Exception e) { }

      try {
	 M1 m1 = new M1 (false, this);
	 M1 m2 = new M1 (false, this);
	 W1 w1 = new W1 (1, m1);
	 W1 w2 = new W1 (2, m2);
	 W1 w3 = new W1 (3, m1);
	 N1 n1 = new N1 (99, m1);
	 w1.start();
	 w2.start();
	 w3.start();
	 n1.start();
      } catch (Exception e) { }
   }
}

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