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何时才能被刷新?