public class Test {
static Boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(() -> {
int a = 0;
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(a++ + flag.toString());
}
});
Thread thread2 = new Thread(()->{
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = !flag;
}
});
thread1.start();
thread2.start();
}
}
无论是否加volatile关键字,thread2对flag变量的修改对thread1始终都是可见的。
static是让类的所有实例对象 共享 类的属性或者方法,理解为“可见性”不太准确,应该理解为“共享”;
volatile是Java内存模型里面的可见性;