CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Threads

Threads
Synchronize threads
Communicate among threads

How to use the wait, notify, and notifyAll methods to communicate among threads

  • Use the wait(), notify(), and notifyAll() methods to facilitate communication among threads. The wait, notify, and notifyAll methods allow the threads in a multithreaded application to inform one another when certain events have occurred or conditions have been met.
  • The wait(), notify(), and notifyAll() methods must be called in a synchronized method or a synchronized block on the calling object of these methods. Otherwise, an IllegalMonitorStateException would occur.
    • The wait method releases the lock on the current object so that other threads can execute synchronized methods. The effect is to interrupt the current thread until another thread calls the notify or notifyAll method.
    • The notifyAll method wakes up all of the threads that are waiting for the current object's lock. The Java thread scheduler then selects one of the threads for execution.
    • The notify method wakes up only one arbitrarily selected thread. Since this thread may not be able to perform its function, the notifyAll method is typically used instead.

Example

  • The wait(), notify(), and notifyAll() methods must be called in a synchronized method or a synchronized block on the receiving object of these methods. Otherwise, an IllegalMonitorStateException will occur.
  • When wait() is invoked, it pauses the thread and simultaneously releases the lock on the object. When the thread is restarted after being notified, the lock is automatically reacquired.
  • The wait(), notify(), and notifyAll() methods on an object are analogous to the await(), signal(), and signalAll() methods on a condition.

A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.

Previous | Create | wait and notifyAll methods | Communicate among threads | Next