Thursday, July 30, 2009

Interthread Communication

In this section, you'll learn about the basic methods used to allow threads to communicate with other concurrently running threads.

Methods for Interthread Communication

public final void wait()
Causes this thread to wait until some other thread calls the notify or notifyAll method on this object. May throw InterruptedException.

public final void notify()
Wakes up a thread that called the wait method on the same object.

public final void notifyAll()
Wakes up all threads that called the wait method on the same object.

Java Tutorial: Interthread Communication

For a clearer understanding of these methods, let us consider the waiter-customer scenario. In a restaurant scenario, the waiter waits until a customer enters the place instead of continually asking people if they want to order or need anything. When a customer comes in, this signifies the customer's interest in ordering food from the restaurant. In a way, the customer by entering the restaurant notifies the waiter that he is need of his service. However, it is not always the case that the customer is immediately ready with his order. It would be annoying if the waiter continually asks the customer if he's ready with his order every once in a while. Instead, the waiter waits until the customer notifies him that he's ready. Once the customer finished giving his orders, it would be annoying for him to continually nag the waiter if he's order is ready. Normally, a customer would wait until the waiter notifies him and serves the food.

Observe that in this scenario, a party that waits only wakes up once the other party notifies him. The same is true for threads.

No comments:

Post a Comment