在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的变量,每次都是从存储区中读取变量对应的值,而不是在该线程中本地缓存的值。因为本地缓存的值不能及时反映其他线程对这个变量的影响。
在线程中 该关键字还是会用到的..