java 多线程-volatile写后立即读
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}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。