1.volatile 与 happens-before
happens-before 是用来判断是否存在数据竞争、线程是否安全的主要依据,它保证了多线程环境下的可见性。下面我们就那个经典的例子,来分析 volatile 变量的读写,如何建立的 happens-before 关系。
public class VolatileTest {
int i = 0;
volatile boolean flag = false;
// Thread A
public void write(){
i = 2; // 1
flag = true; // 2
}
// Thread B
public void read(){
if(flag) {
// 3