java多线程可见性问题
flag先true后false导致不可见性,而且加sout和sleep会恢复,先false后true也不会发生可见性问题
public class VisibilityDemo01 {
public static void main(String[] args) {
MyThread01 t = new MyThread01();
t.start();
while (true){
if (t.isFlag()){
System.out.println("entry");
}
} //flag先true后false导致不可见性,而且加sout和sleep会恢复
//先false后true不会
}
}
class MyThread01 extends Thread {
public boolean flag = false;
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = true;
System.out.println(flag);
}
public boolean isFlag() {
return flag;
}
}
//这个不会发生可见性问题