为什么需要JMM(Java Memory Model)?
- C语言不存在内存模型的概念,很多行为依赖于处理器,不同处理器的操作会导致运行结果不一样,所以不能保证并发安全
- JMM是一组规范,也是工具类和关键字的原理
- JMM最重要的三点内容:重排序、可见性、原子性
一、重排序
1、重排序例子
-
下面是一个演示重排序的例子,一个线程执行
a = 1; x = b
,一个线程执行b = 1; x = b
public class OutOfOrderExecution { private static int x = 0, y = 0; private static int a = 0, b = 0; public static void main(String[] args) throws InterruptedException { //计数器 int i = 0; for (;;) { i++; x = 0; y = 0; a = 0; b = 0; //保证两个线程同时开始执行 CountDownLatch latch = new CountDownLatch(3); Thread one = new Thread(new Runnable() { @Override public void run() { try { latch.countDown(); latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } a = 1; x = b; } }); Thread two = new Thread(new Runnable() { @Override public void run() { try { latch.countDown(); latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } b = 1; y = a; } }); two.start(); one.start(); latch.countDown(); one.join(); two.join(); String result = "第" + i + "次(" + x + "," + y + ")"; //四种情况:0,1/1,0/1,1/0,0 if (x == 0 && y == 0