2015-04-17 49 views
4

我想制作一个简单的线程程序,以1,2,3的顺序启动3个线程,之后按顺序停止3,2,1,只需使用sleep()方法。但是,每次线程都以不同的顺序启动。使线程在Java中以特定顺序启动

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

_...线程...以特定的顺序...仅使用sleep()._ Thread.sleep()对于演示是可以的,但不要依赖它来同步重要程序中的线程。任何'sleep(n)'调用都可以持续更长的时间,而不是'n'毫秒,特别是在加载的系统上。即使它不会持续很长时间,重复睡眠的程序也会累积累积误差。如果您想要保证以特定顺序发生的事情发生,那么您应该使用有保证的同步对象(信号量,队列,倒计数锁存器等) –

回答

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"); 
} 
+0

谢谢,先生。 – Nikola

+4

他们是以正确的顺序开始的,但不能保证他们会**以相同的顺序运行** – jamp

+0

@jamp是的,绝对。这也是导致这种随机输出的一个因素。 –

0

您可以使Util类,巫婆必须是线程安全的,并使同步方法进行打印。

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

现在在Thread1中,Thread2和Thread3使用此Utils.printStuff(“Text”)在控制台中进行打印。

+1

这无助于获得所需的输出,因为无法预知几个并发线程中的哪个特定线程将首先获得该隐式锁。通过'synchronized'锁定总是不公平的。顺便说一句,'System.out.println()'已经同步。 –

+0

输出: 线程1个运行... 线程2运行... 线程3运行... 线程3已终止 线程2已终止 线程1已经终止 但你是对的,是没有保修期望的输出。 – chilltouch