2011-04-15 71 views
30

我一直在尋找的AtomicInteger類中,我遇到下列方法來:在Java for循環中,兩個分號意味着什麼?

/** 
* Atomically increments by one the current value. 
* 
* @return the previous value 
*/ 
public final int getAndIncrement() { 
    for (;;) { 
     int current = get(); 
     int next = current + 1; 
     if (compareAndSet(current, next)) 
      return current; 
    } 
} 

有人能解釋什麼for(;;)手段?

回答

48

它相當於while(true)

一種用於環有三個要素:

  • 初始化
  • 條件(或終止表達)
  • 增量表達

for(;;)不設定任何一個,使其成爲一個無盡的循環。

參考:The for statement

+3

應該指出的是,傳統的'for(;;)'是規範的無限循環,特別是在C中。 – 2011-04-15 13:05:04

3

這只是無限循環的另一種變化,就像while(true){}一樣。

9

這是同樣的事情

while(true) { 
    //do something 
} 

...只是一點點不太清楚。
請注意,如果compareAndSet(current, next)將評估爲true,則循環將退出。

+2

不太清楚,但它仍然是規範的無限循環。 – 2011-04-15 12:53:41

+0

這是真的(+1),它是規範的,但不太清楚。 ;) – 2011-04-15 12:54:39

2

這是一個永遠循環。它只是一個沒有定義條件的循環。

2

這是一個無限循環,如while(true)

29

我會在這裏留下這個以防萬一你是一個視覺學習者。 :)

enter image description here