java内存模型(JMM)
2022-03-23 00:15:08 1 举报
java内存模型(JMM)
作者其他创作
大纲/内容
探秘volatile加不加的区别
read
工作内存
线程2
use
flag=false
load
flag=true
主内存
package com.john.study.jmm;public class JavaMemoryModel01Test { private static boolean flag =false; public static void main(String[] args) throws InterruptedException { new Thread(()->{ System.out.println(\"waiting data...\"); while (!flag){ } System.out.println(\"=========success\"); }).start(); Thread.sleep(2000L); new Thread(()->modefyFlag()).start(); } public static void modefyFlag() { System.out.println(\"prepare data\"); flag=true; System.out.println(\"prepare data end...\"); }}
init Flag=false
assign
flag=false---> flag=true
静态变量不加volatile关键字,某一线程修改了从主存的数据其他线程不可见,
CPU
加volatile关键字
线程1
总线
总结:加了volatile关键字后,又线程修改,其他线程能够立马感知到
write
总线(缓存一致性协议)
不加volatile关键字
总线嗅探机制(监听)
package com.john.study.jmm;public class JavaMemoryModel01Test { private static volatile boolean flag =false; public static void main(String[] args) throws InterruptedException { new Thread(()->{ System.out.println(\"waiting data...\"); while (!flag){ } System.out.println(\"=========success\"); }).start(); Thread.sleep(2000L); new Thread(()->modefyFlag()).start(); } public static void modefyFlag() { System.out.println(\"prepare data\"); flag=true; System.out.println(\"prepare data end...\"); }}
store
0 条评论
下一页