可见性问题:
public class VisibilityDemo {
private boolean flag = true;
public static void main(String[] args) throws InterruptedException {
VisibilityDemo demo1 = new VisibilityDemo();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (demo1.flag){
I++;
}
System.out.println("i="+i);
}
});
thread1.start();
TimeUnit.SECONDS.sleep(2);
demo1.flag = false;
System.out.println("被设置为false");
}
}
问题:指令重排
jvm文档:
https://docs.oracle.com/javase/specs/jvms/se8/html/index.html
cpu缓存可能导致的不一致可以通过volatile解决