Can you show notify not affecting threads in different monitor?

Prev      Next

Answer: Yes - compile and try it

Q63.java    M1.java    W1.java    N1.java   

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

   public M1 (boolean flag) {  this.flag = flag; }

   synchronized public void a () {
      System.out.println("a: wait ("+((W1)Thread.currentThread()).numb+")");
      try { wait(); } catch (Exception e) {}
      System.out.println("a: rise ("+((W1)Thread.currentThread()).numb+")");
   }

   synchronized public void b () {
      System.out.println("b: notify ("+((N1)Thread.currentThread()).numb+")");
      if (flag) notify(); else notifyAll();
      System.out.println("b: done ("+((N1)Thread.currentThread()).numb+")");
   }
}

class N1 extends Thread {
   M1 monitor;
   int numb;

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

   public void run () {
      System.out.println("N1: Starting ("+numb+")");
      monitor.b();
      System.out.println("N1: Finishing ("+numb+")");
   }
}

class W1 extends Thread {
   M1 monitor;
   int numb;

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

   public void run () {
      System.out.println("W1: Starting ("+numb+")");
      monitor.a();
      System.out.println("W1: Finishing ("+numb+")");
   }
}

// Simple test of notify, wait, synchronize
// Only w1 and w3 finish because w2 was not awakened
public class Q63 {
   public static void main (String arg[]) {
      M1 m1 = new M1 (false);  // Use notifyAll()
      M1 m2 = new M1 (false);  // Use notifyAll()
      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();
      System.exit(1);
   }
}