2015-04-17 31 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