可见性、原子性、有序性

2020/12/28 posted in  并发基础

并发的核心矛盾便是CPU、内存、I/O之间的速度差异。

缓存导致的可见性

一个线程对共享变量的修改,另一个线程立即可见

多核CPU缓存与内存的关系图

导致问题示例代码

public class Test {
  private long count = 0;
  private void add10K() {
    int idx = 0;
    while(idx++ < 10000) {
      count += 1;
    }
  }
  public static long calc() {
    final Test test = new Test();
    // 创建两个线程,执行add()操作
    Thread th1 = new Thread(()->{
      test.add10K();
    });
    Thread th2 = new Thread(()->{
      test.add10K();
    });
    // 启动两个线程
    th1.start();
    th2.start();
    // 等待两个线程执行结束
    th1.join();
    th2.join();
    return count;
  }
}

线程切换带来的原子性

一个或者是多个操作在CPU执行过程中不会被中断的特性

非原子操作

编译优化带来的有序性

异常执行