大家好,今天闲聊一下以前困扰过我的一个问题:
这段代码的运行结果是啥?
public static Integer integer = 0;
public static void main(String[] args) throws Exception {
new Thread(() -> {
while (integer == 0){
}
System.out.println("end");
}).start();
Thread.sleep(1000);
System.out.println("update");
integer = 1;
}
是的,程序会一直死循环,很奇怪吧?我明明把integer改成1了,讲道理应该能打印end并正常退出啊?
想要程序正常退出,有两个方法:
1、用volatile修饰integer
2、在while 循环中加一句System.out.println();
关于这两个解决方案,很多人都会觉得是可见性的原因,或者是因为println方法有synchronized修饰,导致强制刷新工作内存到主存,从而保证了可见性。
其实不是这样的,使用volatile以及加一句sout能正常退出都是因为它们阻止了JIT的即时编译
实际上在虚拟机的优化下,这段代码是这个样子的:
public static Integer integer = 0;
public static void main(String[] args) throws Exception {
new Thread(() -> {
while (true){
}
System.out.println("end");
}).start();
Thread.sleep(1000);
System.out.println("update");
integer = 1;
}
有人可能还是觉得和println方法的synchronized有关,实际上是大错特错的!如果是这样的话,读者可以试试用println方法做一下可见性实验(即两个线程进行i++,同时每次打印一下i的值)论证一下。
还是保持怀疑观点的同学可以看看R大的解释:传送门
最后再多一句嘴,加个-Xint也可以解决问题: