«

Java内存模型-volatile原子性

晨曦 发布于 阅读:59 Java基础


/**
 * @Description:Java内存模型-原子性
 * @Author:chenxi
 * @Date:2020/3/22
 **/
public class JMMAtomicityTest {

    private static volatile int counter = 0;

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    counter++;
                }
            }).start();
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(counter);//three result: 9202 9560 9861
    }
}

以上程序运行三次返回结果如下:9202 -> 9560 -> 9861

此时2个线程分别做了counter++,实际写入主内存的值却只有1。