wait() and notify() must only be issued inside a synchronized block : synchronized « Thread « Java Tutorial






public class WaitComm {
  public static void main(String args[]) {
    WFlagSend s = new WFlagSend();
    WFlagRec r = new WFlagRec(s);
    Thread st = new Thread(s);
    Thread rt = new Thread(r);
    rt.setDaemon(true); 
    st.start();
    rt.start();
    try {
      st.join(); 
      while (s.isValid) { 
        Thread.sleep(100);
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

class WFlagSend implements Runnable {
  volatile int theValue;

  boolean isValid;

  public void run() {
    for (int i = 0; i < 5; i++) {
      synchronized (this) {
        while (isValid) {
          try {
            this.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
      theValue = (int) (Math.random() * 256);
      System.out.println("sending " + theValue);
      synchronized (this) {
        isValid = true;
        this.notify();
      }
    }
  }
}

class WFlagRec implements Runnable {
  WFlagSend theSender;

  public WFlagRec(WFlagSend sender) {
    theSender = sender;
  }

  public void run() {
    while (true) {
      synchronized (theSender) {
        while (!theSender.isValid) {
          try {
            theSender.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
      System.out.println("received " + theSender.theValue);
      synchronized (theSender) {
        theSender.isValid = false;
        theSender.notify();
      }
    }
  }
}








10.11.synchronized
10.11.1.Test Synchronized method
10.11.2.Test Unsynchronized method
10.11.3.This program is not synchronized.
10.11.4.This program uses a synchronized block.
10.11.5.Flag Communication
10.11.6.Waiting on an object
10.11.7.wait() and notify() must only be issued inside a synchronized block
10.11.8.guarantee that threads are woken in the same order in which they waited
10.11.9.creating a piped communications system between two threads.
10.11.10.Handle concurrent read/write: use synchronized to lock the data
10.11.11.A synchronized collection with Collections.synchronizedCollection
10.11.12.Determining If the Current Thread Is Holding a Synchronized Lock