Both wait() and notify() must be called in synchronized code. : Wait Notify « Thread « SCJP






class MyData {
  private boolean request;
  private String data;

  public synchronized void storeMessage(String data) {
    while (request == true) {
      try {
        wait();
      } catch (InterruptedException e) {
      }
    }
    request = true;
    this.data = data;
    notify();
  }

  public synchronized String retrieveMessage() {
    while (request == false) {
      // No data to retrieve
      try {
        wait();
      } catch (InterruptedException e) {
      }
    }
    request = false;
    notify();
    return data;
  }
}








7.8.Wait Notify
7.8.1.Wait and Notify
7.8.2.Block and wait
7.8.3.Both wait() and notify() must be called in synchronized code.
7.8.4.Using Wait() and Notify() to Control Access to a Shared Resource