Running Threads In Sequence in Java

Running Threads In Sequence in Java. OR
Run Threads Sequentially in Java. OR
To Execute the Threads one after another in Java. OR
Synchronizing Threads in Java OR
Java Program to execute Threads in sequential order.


Running Threads In Sequence in Java. for sequential execution or to execute threads one after another in Java, threads must be Synchronized in Java. 

This is the famous interview question for the beginners, 
Write a 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.

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

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted 

Count trailing zeros in factorial of a number 

When to use SOAP over REST Web Service. Is REST better than SOAP? 

Tower Of Hanoi Program in Java. 

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

Post a Comment