volatile
线程对变量进行修改后,立刻写回到主内存
线程对变量读取的时候,从主内存中读取,而不是缓冲,避免了指令重排

无法破除循环

public class my {private volatile static int num=0;public static void main(String[]args) throws InterruptedException{ new Thread(()->{ while(num==0) { } }).start(); Thread.sleep(1000); num=1; //理论上1秒后停止,因为死循环没有办法同步num}}

修改后:

public class my {private volatile static int num=0;public static void main(String[]args) throws InterruptedException{ new Thread(()->{ while(num==0) { } }).start(); Thread.sleep(1000); num=1; //理论上1秒后停止,因为死循环没有办法同步num}