在java 線程 3rd中3.2講到了一個(gè)少用的關(guān)鍵字 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類型應(yīng)該就已經(jīng)是原子操作了,不需要再保證了。 ?
? ?
? 書(shū)里說(shuō) ? stop標(biāo)志必須是volatile的,以便run()方法肯定看到他(否則的話,這個(gè)值可能本地緩存) ?
? ?
? 我猜想 ? volatile表示這個(gè)值可能被別的線程改變,所以被標(biāo)志為volatile的變量,每次都是從存儲(chǔ)區(qū)中讀取變量對(duì)應(yīng)的值,而不是在該線程中本地緩存的值。因?yàn)楸镜鼐彺娴闹挡荒芗皶r(shí)反映其他線程對(duì)這個(gè)變量的影響。???
?
在線程中 該關(guān)鍵字還是會(huì)用到的..