public class JmmDemo {
private static int temp = 1;
private static int ans = 0;
static class THread implements Runnable {
@Override
public void run() {
while (true) {
ans++;
if (ans == 1000) {
break;
}
System.out.println(temp + "b");
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new THread()).start();
Thread.sleep(1000);
temp = 2;
}
}
这个代码打印一直是1b不会出现2b(首先我的cpu是I5 6200u, a家的u不知道会怎么样有兴趣的可以自己试试)。这里的结果和大部分介绍volatile的文章的结果一样。但是那么接下来换一下
public class JmmDemo {
private static int temp = 1;
static class THread implements Runnable {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println(temp + "b");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new THread()).start();
Thread.sleep(1000);
temp = 2;
}
}
这个代码会打印出2b,为什么呢?
我觉得是因为sleep以后线程放弃了cpu,使得工作线程内存有时间更新主内存的数据,导致了这个现象(迫真)