2016-09-18 52 views
0

我使用​​爲了執行第一個線程,然後在第一個線程完成時執行另一個線程,但是兩個線程同時執行。爲什麼?當我使用'synchronized'時,爲什麼我的線程不會一個接一個地執行?

public class PrintNums extends Thread { 
    int num; 

    public PrintNums(int x) { 
     this.num = x; 
    } 

    @Override 
    public void run() { 
     this.count(); 
    } 

    public synchronized void count() { 
     for (int i = 1; i <= 5; i++) { 
      System.out.println((2 * i - this.num)); 
      try { 
       Thread.currentThread().sleep(1000); 
      } catch (InterruptedException ex) { 
      } 
     } 
    } 

    public static void main(String[] args) { 
     PrintNums odd = new PrintNums(1); 
     PrintNums even = new PrintNums(0); 

     odd.start(); 
     even.start(); 
    } 
} 
+2

同步用於訪問特定對象(即,同步到一個對象)。你有兩個不同的對象('odd'和'even')。 –

+1

[爲什麼這種同步方法不能按預期工作?](http://stackoverflow.com/q/26610791) – Tom

回答

2

​​沒有一個明確的目標意味着synchronized(this):每個線程本身同步,所以沒有衝突。如果你想序列化它們,你可以使用synchronized(PrintNums.class)

請注意,通常比使用顯式線程更好的構造,例如執行器或鎖存器。

+0

感謝您的解釋,我想我明白了原因吧! –

相關問題