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 –
This method waits until the thread on which it is called terminates.
public final void join() throws InterruptedException
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
You may also like -