Suppose I have the following class below, how can I force the three threads to be executed in order, one after the other successively? (waiting for each other to be terminated)
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("Thread 1 :First Thread started");
}
public static Runnable delay(){
Runnable r = new Runnable(){
@Override
public void run() { // running state
System.out.println("Thread 2: loading second thread..");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: System loaded");
}
}; // finished state
return r;
}
public static Runnable waiting(){
Runnable r = new Runnable(){
@Override
public void run() { // running state
System.out.println("Thread 3: waiting..");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 3: OK");
}
}; // finished state
return r;
}
public static void main(String[] args) throws InterruptedException{
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(delay());
Thread thread3 = new Thread(waiting()); // (initial state)
thread1.start();
thread2.start();
thread3.start();
}
}