Sunday, 25 June 2017

wait notify notifyall example in Java Thread.

wait notify notifyall example in Java.


wait notify notifyall example in Java Thread. how wait notify notifyAll works in Java. difference between wait, notify and notifyAll in java thread. 

wait() :
Thread on which wait() method is called will go to waiting state by releasing the monitor(here monitor is nothing but object of any class).
Note: This thread will wake up only if some other thread calls either notify or notifyAll on same monitor.

notify() :
Thread on which notify() method is called will wake up one thread who is waiting on same monitor.

notifyAll() :
Thread on which notifyAll() method is called will wake up all threads who is waiting on same monitor.
 

We will understand wait(), notify(), notifyAll() with the help of below program that creates 3 threads and prints alternate values in sequence.

Input: 
We have three Threads, ThreadA, ThreadB and ThreadC each printing "A", "B" and "C" repectively.

Output:
 

A B C A B C A B C A ...... so on.

Printing Threads in Sequence in Java.


We have 3 threads as shown below,

ThreadA is printing "A" continuously. (ThreadA.java)
ThreadB is printing "B" continuously. (ThreadB.java) 
ThreadC is printing "C" continuously. (ThreadC.java)

If we will not synchronize above threads then the output order is not guaranteed and we may get output like 
A C B B B C A A B C A A C C .... or
A C C C C C A A B C B B B B .... or anything

but the desired output is A B C A B C A B C A B C A B C......

For this, we need to synchronize ThreadA, ThreadB and ThreadC? what does synchronize mean here? 
Synchronize in simple terms is to allocate a turn to ThreadA as when it should run, allocate a turn to ThreadB as when it should run, allocate a turn to ThreadC as when it should run.

We took one variable "flag" and synchronize 3 threads as below, 
If value of flag=1, then it is ThreadA's turn to print.
If value of flag=2, then it is ThreadB's turn to print.
If value of flag=3, then it is ThreadC's turn to print. 

Now question is,
what will ThreadA do if flag value is 2 or 3 ? ThreadA will wait() as it is not his turn.
what will ThreadB do if flag value is 1 or 3 ? ThreadB will wait() as it is not his turn..
what will ThreadC do if flag value is 1 or 2 ? ThreadC will wait() as it is not his turn.

Thread can call wait() method, but wait() method needs to be called on some object. 
In our case, we will create class "ResourceLock", which will be used as a lock for all 3 threads and wait() method will be called on object of "ResourceLock".

What is the task of ThreadA,
  1. ThreadA should first acquire lock on the object of "ResourceLock", 
  2. ThreadA should check whether value of flag is 1,
  3. If No, then wait().
    If Yes,
    then print "A" and set the flag value to "2" for marking ThreadB's task as next.
    Notify all the waiting threads by using notifyAll() method.
Once notified, all waiting Threads will be waked up, that is ThreadB and ThreadC will be awake now, but as the value of flag is 2, only ThreadB will be active and other Threads will again go in waiting state.


Java Program to execute Threads in sequential order.


 ThreadRunningInSequence.java

package javabypatel;

public class ThreadRunningInSequence {

    public static void main(String[] args) {

     ResourceLock lock = new ResourceLock();

        ThreadA a=new ThreadA(lock);
        ThreadB b=new ThreadB(lock);
        ThreadC c=new ThreadC(lock);

        a.start();
        b.start();
        c.start();
    }
}
ThreadA.java
package javabypatel;

public class ThreadA extends Thread{

 ResourceLock lock;

 ThreadA(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=1){
      lock.wait();
     }

     System.out.print("A ");
     Thread.sleep(1000);
     lock.flag = 2;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 1 :"+e.getMessage());
  }

 }

}


ThreadB.java
package javabypatel;

public class ThreadB extends Thread{

 ResourceLock lock;

 ThreadB(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=2){
      lock.wait();
     }

     System.out.print("B ");
     Thread.sleep(1000);
     lock.flag = 3;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 2 :"+e.getMessage());
  }

 }
}

ThreadC.java
package javabypatel;

public class ThreadC extends Thread{

 ResourceLock lock;

 ThreadC(ResourceLock lock){
  this.lock = lock;
 }

 @Override
 public void run() {

  try{
   synchronized (lock) {

    for (int i = 0; i < 100; i++) {

     while(lock.flag!=3){
      lock.wait();
     }

     System.out.print("C ");
     Thread.sleep(1000);
     lock.flag = 1;
     lock.notifyAll();
    }

   }
  }catch (Exception e) {
   System.out.println("Exception 3 :"+e.getMessage());
  }

 }
}


ResourceLock.java
package javabypatel;

public class ResourceLock{
 public volatile int flag = 1;
}

You may also like to see


Java Multithreading and Concurrency Interview Questions and Answers with Example

Advanced Multithreading Interview Questions In Java

How ConcurrentHashMap works and ConcurrentHashMap interview questions.

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

Enjoy !!!! 
If you find any issue in post or face any error while implementing, Please comment.

No comments:

Post a Comment