老师,为什么线程1中的while循环不会结束?
来源:1-5 JAVA内存模型
奥观海同志
2021-01-14
public class YuanThread {
private Boolean flag = true;
public void refresh() {
System.out.println(Thread.currentThread().getName() + "refresh flag");
flag = false;
}
public void forS() {
System.out.println(Thread.currentThread().getName() + "开始执行");
int i = 0;
while (flag) {
i++;
// System.out.println();
// sleep(100000);
// sleep(1000);
}
System.out.println(Thread.currentThread().getName() + "跳出循环i=" + i);
}
public static void main(String[] args) {
YuanThread yuanThread = new YuanThread();
new Thread(() -> {
yuanThread.forS();
}, "thread1").start();
try {
Thread.sleep(2000);
new Thread(() -> {
yuanThread.refresh();
}, "thread2").start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void sleep(long interval) {
long start = System.nanoTime();
long end;
do {
end = System.nanoTime();
} while (start + interval > end);
}
}
i++ 下面增加不同耗时的操作,则有可能使循环结束。为什么thread1没有及时获取到thread2修改过的值呢?thread1的工作内存中的flag何时才能被刷新?
写回答
1回答
-
Jimin
2021-01-17
你好,要保证各个线程都能读到最新的值,要使用volatile,每次强制读取最新的值
042021-01-24
相似问题