2014-09-10 51 views
-4
public class Test implements Runnable { 

    static int i; 

    public void run() { 

     System.out.println(i); 
    } 

    public static void main(String[] args) { 

     Test t=new Test(); 

     for(i=0;i<=5;i++){ 
      Thread t1=new Thread(t); 
      t1.start(); 
      System.out.println("The main method:"+i); 
     } 
    } 

} 

答案我得到一個循環是: -DONOT明白爲什麼答案是正在添加6時,我有5

The main method:0 
0 
The main method:1 
2 
The main method:2 
The main method:3 
The main method:4 
5 
The main method:5 
6 
6 
6 

回答

2

編輯:現在我看到i是一個靜態變量,未聲明在循環。達到6的原因是它增加,直到循環的條件i <= 5不再爲真,這發生在i達到6時。

+0

他確實發佈了他的'Test'類,但它沒有正確縮進 – 2014-09-10 11:49:38

+0

@Thüzhen感謝您的評論。 – Eran 2014-09-10 11:56:04

0

這是因爲i<=5。包括0,i<5重複5次(從0開始並在4結束)。如果您添加=,您將「強制」代碼停止在5,迭代5 + 1次。

這種錯誤被稱爲off-by-one,雖然它當你開始編程它可能會導致災難性的錯誤是一種常見的錯誤(例如,見this famous bug in OpenSSL

0

的所有線程共享一個單一static int i;

環路在main啓動線程,而我是(仍然!)0,1,2,3,4,5,但他們會執行一些延遲。同時,主循環繼續進行,並且您會看到一些後來的狀態。

請注意,某些值缺失,其他值重複,並且存在神祕的6,這是循環退出時的設置,其中一些線程尚未到達println。

相關問題