Thursday, May 13, 2010

wait(), notify() and notifyAll()

The wait(), notify() and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.

2 comments:

  1. Why these methods are in Object class and not in Thread class?

    ReplyDelete
  2. Hi Deepak,

    The answer is that Threads can use Objects to transmit messages from one thread to another, and these methods allow that to happen. A Thread calls wait() to say "I am waiting for a message to be sent to this object." Another thread can call notify() to say "I am sending a message to that object." The Object is therefore a conduit through which threads communicate without explicitly referencing each other. If the methods were in the Thread class, then two threads would need to have references to one another to communicate. Instead, all communicating threads just need to agree to use some specific shared resource.

    ReplyDelete