Make threads start in a specific order in Java

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) {
        // TODO Auto-generated catch block
        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) {
        // TODO Auto-generated catch block
        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) {
        // TODO Auto-generated catch block
        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
+4
source share
2 answers

Your threads start in the correct order, but the output may be wrong, because the output messages arrive simultaneously. You must transfer messages to the main thread:

public static void main(String[] args) throws InterruptedException {     
    Thread tr1 = new Thread1();
    Thread tr2 = new Thread2();
    Thread tr3 = new Thread3();
    tr1.start();
    System.out.println("Thread 1 started");
    tr2.start();
    System.out.println("Thread 2 started");
    tr3.start();      
    System.out.println("Thread 3 started");  
}
+5
source

You can create a Util class that should be thread safe and make a synchronized method for printing. A.

public class Utils {
      public static synchronized void printStuff(String msg) {
             System.out.println(msg);
      }
}

Thread1 Thread2 Thread3 Utils.printStuff( "" ) .

0

All Articles