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

Home
SCJP
1.Java Source And Data Type
2.Operators
3.Modifiers
4.Type Casting
5.Statements
6.Object Oriented
7.Thread
8.Utility Classes
9.File
SCJP » Thread » Wait Notify 
7.8.3.Both wait() and notify() must be called in synchronized code.
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.