1.volatile
关键是一种相较于synchronized较为轻量级的同步策略。
2.volatile
不具备互斥性,volatile
不能保证变量的原子性。
3.volatile
关键字保证了不同的线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这个新的值对于所有线程是可见的。
4.volatile
禁止指令重排。
public class VolatileDemo {
private static boolean flag = false;
public static void main(String[] args) {
System.out.printf("当前线程为:[%s]\n", Thread.currentThread().getName());
new Thread(new Runnable() {
@Override
public void run() {
while (!flag);
System.out.printf("当前线程为:[%s]\n", Thread.currentThread().getName());
}
}).start();
sleep(2000);
flag = true;
}
private static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class VolatileDemo {
private static volatile boolean flag = false;
public static void main(String[] args) {
System.out.printf("当前线程为:[%s]\n", Thread.currentThread().getName());
new Thread(new Runnable() {
@Override
public void run() {
while (!flag);
System.out.printf("当前线程为:[%s]\n", Thread.currentThread().getName());
}
}).start();
sleep(2000);
flag = true;
}
private static void sleep(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
多级cache结构 -> 缓存一致性协议(MESI)-> store buffer和invalidate queue -> 内存屏障
https://www.cnblogs.com/xrq730/p/7048693.html
https://juejin.cn/post/6844903520760496141
https://crossoverjie.top/2018/03/09/volatile/