为什么这样用volatile修复的变量并没有保证可见性
两次new VolatileTest() ,表示创建了两个对象,但是flag并不是静态属性。加上static试试
public class Test {
// 当用volatile修饰时会打印1, 把volatile换成static时不会打印1的
volatile Boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
test.test();
Thread.sleep(500);
test.test2();
}
public void test() {
new Thread(() -> {
while(flag) {
}
System.out.println(1);
}).start();
}
public void test2() {
new Thread(() -> {
flag = false;
}).start();
}
}
你的例子中new了两个对象,和volatile根本就无关了