直接上代码:以下代码中启动线程load和refresh。对于静态成员变量flag,在load中设置死循环,在refresh中设置条件破坏load中的死循环。在load启动后主线程休眠1秒,再让refresh执行。
public class ResearchVolatile {
private static boolean flag = true;
private static long count = 0;
public static void main(String[] args) throws InterruptedException {
Thread load = new Thread(() -> {
System.out.println("开始循环");
while (flag) {
count++;
}
System.out.println("跳出了循环,循环的次数是:" + count);
});
Thread refresh = new Thread(() -> {
flag = false;
System.out.println("设置flag为false");
});
load.start();
// 先执行A,进入A的循环体
Thread.sleep(1000);
refresh.start();
}
}
运行结果:当线程refresh中的flag条件改变后,发现load中的循环体并没有改变,并且一直在死循环中。
&nbs