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
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).