禁用CPU 缓存
告诉编译器,对这个变量的读写,不能使用 CPU 缓存,必须从内存中读取或者写入
/**
* TODO 在此写上类的相关说明.<br>
* @author gqltt<br>
* @version 1.0.0 2020年4月8日<br>
* @see
* @since JDK 1.5.0
*/
public class VolatileExample {
int x = 0;
volatile boolean b = false;
public void writer() {
x = 42;
b = true;
}
public void reader() {
if(b) {
System.out.println("x=" + x);
}
}
/**
* @param args
*/
public static void main(String[] args) {
VolatileExample example = new VolatileExample();
Thread th1 = new Thread(()->{
CommonUtil.sleep(100);
example.writer();
});
Thread th2 = new Thread(()->{
CommonUtil.sleep(300);
example.reader();
});
th1.start();
th2.start();
try {
th1.join();
th2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1、根据规则1,x=42 Happens-Before v=true
2、根据规则2,写变量v=true Happens-Before 读变量 v=true
3、根据规则3,x=42 Happens-Before 读变量 v=true