使线程在Java中以特定顺序启动

Nik*_*ola 4 java multithreading

我想创建一个简单的线程程序,它按1,2,3顺序启动3个线程,之后只需使用sleep()方法按顺序3,2,1停止.但是,每次线程以不同的顺序开始.

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();        
}
Run Code Online (Sandbox Code Playgroud)

电流输出:

Thread 1 running...
Thread 3 running...
Thread 2 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
Run Code Online (Sandbox Code Playgroud)

期望的输出:

Thread 1 running...
Thread 2 running...
Thread 3 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated
Run Code Online (Sandbox Code Playgroud)

Ale*_*you 5

您的线程以正确的顺序启动,但输出可能是错误的,因为输出消息同时到达.您应该将消息传递到主线程:

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");  
}
Run Code Online (Sandbox Code Playgroud)

  • 它们以正确的顺序启动,但不保证它们将以相同的顺序运行**... (4认同)