Tuesday, February 13, 2018

Java thread wait, notify and notifyAll Methods Examples

Inter communication between thread is one of the most important topic now a days asked in interview questions.i.e wait() , notify() , notifyAll()

If you dont know the basics of Multithreading see my previous posts
Multithreading in java 
Basics of Volatile Keywords

What is Wait , Notify and NotifyAll Method do ?

This method is the part of Object Class which is used to release the lock over the shared resource. Wait has 2 variant , one is where the thread will wait for the resource for infinite time for notify or notifyAll to be call. Other is it wait for specific time which user assigned before wake up.

Notify method is also the part of Object class , It basic responsibility is to notify any one the thread who are waiting for the resource to get lock based on the priority or system implementation
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.

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

These methods can be used for Producer – Consumer Problem on low level synchronization.

Interview Question : print continuous number using 2 thread 

Now we will see how to use the Wait , Notify and NotifyAll In java

Explanation :
  • We have 2 class one is Processor2 and Second is WaitNotifyDemo (main class)
  • In Processor2 class we have 2 methods one is producer() and other is consumer() , In Producer we have first sysout command and then wait() method which will release the lock at wait() line , whereas in consumer() method we are sleeping the thread for 1 sec so that producer will take the lock .
  • Now in consumer method we have created a scanner object where we are looking for the keystroke after the key stoke we are notify() to other threads to get the lock.
  • After this point the thread one which is waiting for the lock in producer() method will get the lock and then print the last sysout.

This program is just to show you how wait and notify works whereas we always use wait in while loop.
We will see the industry level code for wait notify in next post of Producer ConsumerProblem.

I hope this will help you to understand the wait and notify working. If you have any issue please leave us a comment we will be happy to help.

Thanks for reading


Post a Comment