public class ThreadDemo {
private static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
int i = 0;
while (!stop) i++;
System.out.println("i = " + i);
}).start();
TimeUnit.SECONDS.sleep(2);
stop = true;
}
}
public class ThreadDemo2 {
private volatile static boolean stop = false;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
int i = 0;
while (!stop) i++;
System.out.println("i = " + i);
}).start();
TimeUnit.SECONDS.sleep(2);
stop = true;
}
}
value = 3;
"CPU0执行操作"
void cpu0() {
value = 10;
isFinish = true;
}
"CPU1执行操作"
void cpu1() {
if(isFinish) { // true
assert value == 10;// false
}
}
value = 3;
"CPU0执行操作"
void cpu0() {
value = 10;
"屏障指令,强制把缓存的变量同步到主内存里面"
storeMemoryBarrier();
isFinish = true;
}
"CPU1执行操作"
void cpu1() {
if(isFinish) { // true
"强制从主内存获取最新的值"
loadMemoryBarrier();
assert value == 10; // true
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |