I would like to create a simple thread program that starts 3 threads in the order of 1,2,3, and then stops in the order of 3,2,1, just using the sleep () method. However, each time the threads start in a different order.
class Thread1 extends Thread{
public void run(){
System.out.println("Thread 1 running...");
try {
this.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1 has terminated");
}
}
class Thread2 extends Thread {
public void run(){
System.out.println("Thread 2 running...");
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2 has terminated");
}
}
class Thread3 extends Thread {
public void run(){
System.out.println("Thread 3 running...");
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 3 has terminated");
}
}
public static void main(String[] args) throws InterruptedException {
Thread tr1 = new Thread1();
Thread tr2 = new Thread2();
Thread tr3 = new Thread3();
tr1.start();
tr2.start();
tr3.start();
}
current output:
Thread 1 running...
Thread 3 running...
Thread 2 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
desired result:
Thread 1 running...
Thread 2 running...
Thread 3 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
source
share