在java 線程 3rd中3.2講到了一個少用的關鍵字 volatile.
However, Java provides a more elegant solution: the volatile keyword. If a variable is marked as volatile, every time the variable is used it must be read from main memory. Similarly, every time the variable is written, the value must be stored in main memory. Since these operations are atomic, we can avoid the race condition in our example by marking our done flag as volatile.
?
在tij中也有講述
?Thinking ? in?? java?? 的 ? 13.7 ? 范例 ? CanStop ? 里面有代碼 ?
? //Must ? be ? volatile: ?
? private ? volatile ? boolean ? stop ? = ? false; ?
? 這里boolean類型應該就已經是原子操作了,不需要再保證了。 ?
? ?
? 書里說 ? stop標志必須是volatile的,以便run()方法肯定看到他(否則的話,這個值可能本地緩存) ?
? ?
? 我猜想 ? volatile表示這個值可能被別的線程改變,所以被標志為volatile的變量,每次都是從存儲區中讀取變量對應的值,而不是在該線程中本地緩存的值。因為本地緩存的值不能及時反映其他線程對這個變量的影響。???
?
在線程中 該關鍵字還是會用到的..