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

Lambda calculus, Type theory, Formal semantics, Program analysis

       Previous     Next           Test8b.java      TestFrame      Sister code     All lectures

Use the interrupt method to wake up threads

// Determine whether there are other ways to wake up threads
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

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 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 Test8Doer extends Thread {
   TestFrame f;

   public Test8Doer (TestFrame f) { this.f = f; }

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

      M1 m1 = new M1 (false, f);  // Use notifyAll()
      M1 m2 = new M1 (false, f);  // Use notifyAll()
      W1 w1 = new W1 (1, m1);
      W1 w2 = new W1 (2, m2);
      W1 w3 = new W1 (3, m1);
      w1.start();
      w2.start();
      w3.start();

      try { sleep(1000); } catch (Exception e) {}

      w1.interrupt();  // One way to get a waiting thread to go
      f.text.append("\n");
   }
}

class Test8bFrame extends TestFrame {
   public Test8bFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.add(button);
      add("South",p);
      add("Center",new JScrollPane(text));
   }

   public void actionPerformed (ActionEvent evt) {
      (new Test8Doer(this)).start();
   }
}

public class Test8b extends Applet {
   public void init () {
      TestFrame test = new Test8bFrame();
      test.setSize(400,600);
      test.setVisible(true);
   }
}