Wednesday, 12 October 2016

How to run threads in sequence - Java Program

How to make sure that threads run in sequence is a very popular multi-threading interview question. Though it doesn’t make much sense practically to do that as you use threads so that processing can be done by many threads simultaneously. But you have to answer a question if asked in interview so this post tries to gives that answer.

So, if you are asked to answer the question “How can you make sure that Thread t1, t2 and t3 are executed in such a way that t2 starts after t1 finishes and t3 starts after executing t2” you have to say using join() method it can be done.

join() method

join() method is used when you want to wait for the thread to finish. Its general form is –

public final void join() throws InterruptedException
This method waits until the thread on which it is called terminates.

As you see from the description of the join() method if it is called on any thread it will wait until the thread on which it is called terminates. Armed with this info let’s see the code now.

Example code

public class ThreadSequence {

 public static void main(String[] args) {
  SeqRun sr = new SeqRun();
  // Three threads
  Thread t1 = new Thread(sr);
  Thread t2 = new Thread(sr);
  Thread t3 = new Thread(sr);
  
  try {
   // First thread
   t1.start();
   t1.join();
   // Second thread
   t2.start();
   t2.join();
   // Third thread
   t3.start();
   t3.join();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

class SeqRun implements Runnable{

 @Override
 public void run() {
  System.out.println("In run method " + Thread.currentThread().getName());
  
 } 
}

Output

In run method Thread-0
In run method Thread-1
In run method Thread-2

It can be seen that threads are executed in sequence here. Thing to do here is you start the thread and call the join() method on the same thread. This makes it to wait until the thread stops executing. That way order is ensured.

For testing you can also called sleep() method on the thread inside run(), you can observe that other thread doesn’t start their execution even if the current thread is sleeping.

@Override
public void run() {
 try {
  Thread.sleep(1000);
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 System.out.println("In run method " + Thread.currentThread().getName()); 
} 

That's all for this topic How to run threads in sequence - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and wait-notify
  2. Producer-Consumer Java program using ArrayBlockingQueue
  3. String and thread-safety in Java
  4. Race condition in Java multi-threading
  5. Synchronization in Java multithreading

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment