3/13/2014

Communicate between Threads in Java

The Java wait-and-notify mechanism is a way for inter thread communcation in Java. It allows one thread to communicate to another thread that a particular condition has occured. The wait-and-notify mechanism cannot be used to replace the synchronized mechanism and does not solve the race condition problem. In fact, wait-and-notify must be used in conjunction with the synchronized lock to prevent a race condition.

Just like the synchronized mechanism, the wait-and-notify mechanism is available from every object. There are three methods to invoke on any object should have the object monitor.

wait, notify and notifyAll methods in Java doc

  • wait()

    The current thread must own this object’s monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object’s monitor to wake up either through a call to the notify method or the notifyAll method.

  • notify()

    Wakes up a single thread that is waiting on this object’s monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object’s monitor by calling one of the wait methods.

  • notifyAll()

    Wakes up all threads that are waiting on this object’s monitor.

On the other question, wait and notify method are used to put thread on wait but they are not in Thread class along with Sleep() or Join() method instead they are declared in Object class. This article has few reasons which make sense on Why Wait and Notify is in Object Class in Java.

Code for Producer-and-Consumer Problem

No comments:

Post a Comment