How to start one thread after another thread in java?

How to start one thread after another thread in java?



To start one thread after another thread is the functionality we often need in programming. So this makes a good interview question and often asked. You may get question like How to ensure that a thread runs after another ? Or There are thread Thread1, Thread2 and Thread3, how can we ensure that thread Thread2 run after Thread1 and thread Thread3 run after Thread2?

Java provides one method to Thread object which is join() this method simply waits for this thread to die. join() method also has two variants such as join(long millis ) which waits for millis millisecond to die and join(long millis, int nanos) which waits for millis plus nanos to die.

To start one thread after another we need join() method.

As shown in example below we are creating three thread objects and in each thread we are passing runnable objects.

Important thing to note is after starting the thread with start() method we are calling join() method which waits for this thread to die and start another thread which fulfils our requirement


public class ThreadTest {

public static void main(String[] args) {

//creating 3 Thread objects and passing it an object of type Runnable

try{

Thread thread1 = new Thread(new MyRunnable("Thread 1"));

thread1.start();

thread1.join();

Thread thread2 = new Thread(new MyRunnable("Thread 2"));

thread2.start();

thread2.join();

Thread thread3 = new Thread(new MyRunnable("Thread 3"));

thread3.start();

thread3.join();

}catch(Exception es){

es.printStackTrace();

}

}

}

class MyRunnable implements Runnable {

String runnerName = "";

public MyRunnable(String name){

runnerName = name;

}

public void run() {

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

try{

Thread.sleep(3000);

}catch(Exception es){

}

System.out.println(runnerName+" Counting i = " + i);

}

System.out.println("Thread executed!");

}

}

Output

Thread 1 Counting i = 0

Thread 1 Counting i = 1

Thread 1 Counting i = 2

Thread 1 Counting i = 3

Thread 1 Counting i = 4

Thread executed!

Thread 2 Counting i = 0

Thread 2 Counting i = 1

Thread 2 Counting i = 2

Thread 2 Counting i = 3

Thread 2 Counting i = 4

Thread executed!

Thread 3 Counting i = 0

Thread 3 Counting i = 1

Thread 3 Counting i = 2

Thread 3 Counting i = 3

Thread 3 Counting i = 4

Thread executed!
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment