2013-12-20 32 views
-1

當我加入一個線程時,第一個線程需要先運行,然後再運行第二個thrads是否正確?如果是的話,我如何加入Main方法中的兩個線程?我將如何加入兩個線程?

public class SynchronizedThreads implements Runnable { 
    Thread t; 

    public SynchronizedThreads() { 
     t = new Thread(this, "Synched Thread"); 
     t.start(); 
    } 
    public void run() { 
     for(int i = 0; i < 100; i++) { 
      System.out.println(i); 
      try { 
       t.sleep(1000); 
      } 
      catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

public class StartSynchronizedThreads { 
    public static void main(String[] args) { 
     SynchronizedThreads x = new SynchronizedThreads(); 
     SynchronizedThreads y = new SynchronizedThreads(); 
    } 
} 
+1

你要求的'的Thread.join()'方法的文檔? – SLaks

+3

由於對象構造器的競爭條件,在對象構造函數中啓動線程並不是一個好的模式。 – Gray

+0

沒有我有文檔,我試圖找到如何加入主要方法中的x和y對象的兩個線程。 –

回答

0
try { 
    x.t.join(); 
    y.t.join(); 
} catch (InterruptedException e) { 
    System.out.println("Main thread Interrupted"); 
}