• Post Reply Bookmark Topic Watch Topic
  • New Topic

How can threads communicate with each other?  RSS feed

Prateek Kumar Singh
Ranch Hand
Posts: 30
Eclipse IDE Hibernate Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2762
Eclipse IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's your question? Are you asking how wait and notify work internally?
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!