wait() and notify()

public class MyWaitNotify {

  boolean flag;

  synchronized void plus() throws InterruptedException {
    System.out.print("+");
    flag = true;
    notify();
    while (flag) {
      wait();
    }
  }

  synchronized void minus() throws InterruptedException{
    System.out.print("-");
    flag = false;
    notify();
    while (!flag) {
      wait();
    }
  }

  public static void main(String[] args) {
    final MyWaitNotify mwn = new MyWaitNotify();

    new Thread(new Runnable() {

      @Override
      public void run() {
        while (true) {
          try {
            mwn.plus();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();

    new Thread(new Runnable() {

      @Override
      public void run() {
        while (true) {
          try {
            mwn.minus();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }
}

Result:
+-+-+-+-+- …

wait() – suspends the task and waits until another thread wakes it up by calling notify().The waiting task after receiving notify signal checks the condition in the loop and if not met, exits the loop. In this example, the shared monitor is this. We can call notify() and wait() on other instances:
synchronized(sharedMonitor){
    ...
    sharedMonitor.wait();
    ...
    sharedMonitor.notify();
    ...
}

Rules of the thumb:

  • always put all the wait(), notify() and setting condition(s) into synchronized methods
  • put wait() in the loop checking a condition of interest (double security from unexpected behavior when more tasks would be involved)
  • precede notify() with the condition(s) set to value that enables:
    – the same task to enter the loop to reach wait() (meet the condition)
    – the other thread to exist the loop (not meet the condition)
  • Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s