File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes How can threads communicate with each other? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How can threads communicate with each other?" Watch "How can threads communicate with each other?" New topic

How can threads communicate with each other?

Prateek Kumar Singh

Joined: Jan 21, 2011
Posts: 29

Hi Guys,

The wait(), notify(), and notifyAll() methods are used to provide an efficient way for threads to communicate with
each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the
producer thread is completing work that the other thread (consumer thread) will use.

Example: If you imagine an application in which one thread (the producer) writes data to a file while a second
thread (the consumer) reads data from the same file. In this example the concurrent threads share the same
resource file. Because these threads share the common resource file they should be synchronized. Also these
two threads should communicate with each other because the consumer thread, which reads the file, should wait
until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its
writing operation.

Let’s look at a sample code where count is a shared resource. The consumer thread will wait inside the
consume() method on the producer thread, until the producer thread increments the count inside the produce()
method and subsequently notifies the consumer thread. Once it has been notified, the consumer thread waiting
inside the consume() method will give up its waiting state and completes its method by consuming the count (i.e.
decrementing the count).

Jayesh A Lalwani
Saloon Keeper

Joined: Jan 17, 2008
Posts: 2744

What's your question? Are you asking how wait and notify work internally?
I agree. Here's the link:
subject: How can threads communicate with each other?
It's not a secret anymore!