Tuesday, November 13, 2012

wait and notify methods in Java

Java includes an elegant inter-process communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. All three methods can be called only from within a synchronized method. Although conceptually advanced from a computer science perspective, the rules for using these methods are actually quite simple:

  • wait( ) tells the calling thread to give up the monitor and go to sleep until some other
    thread enters the same monitor and calls notify( ).
  • notify( ) wakes up the first thread that called wait( ) on the same object.
  • notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
    highest priority thread will run first.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )

Additional forms of wait( ) exist that allow you to specify a period of time to wait.
InterruptedException is thrown when Thread.interrupt() method is called.

No comments:

Post a Comment