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

时间:2015-04-17 10:52:28

标签: 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();        
}

当前输出:

Thread 1 running...
Thread 3 running...
Thread 2 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated

期望的输出:

Thread 1 running...
Thread 2 running...
Thread 3 running...
Thread 3 has terminated
Thread 2 has terminated
Thread 1 has terminated

2 个答案:

答案 0 :(得分: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");  
}

答案 1 :(得分:0)

你可以制作Util类,必须是线程安全的,并使同步方法打印。

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

现在在Thread1中,Thread2和Thread3使用这个Utils.printStuff(" Text")在控制台中打印。