为什么我在while循环中让main线程休眠100毫秒,也可以解决flag的可见性问题
public class VolatileThreadTest {
public static void main(String[] args) throws InterruptedException {
// 创建VolatileThread线程对象
VolatileThread volatileThread = new VolatileThread();
volatileThread.start();
// main方法
while (true) {
if (volatileThread.isFlag()) {
System.out.println("执行了======");
}
//让线程休眠100毫秒
Thread.sleep(100);
}
}
}
class VolatileThread extends Thread {
// 定义成员变量
private boolean flag = false;
public boolean isFlag() {
return flag;
}
@Override
public void run() {
// 线程休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 将flag的值更改为true
this.flag = true;
System.out.println("flag=" + flag);
}
}