volatile 不具有原子性

volatile 具有可见性,顺序性,但是不具有原子性。

以一个列子来说明:

10个线程对 num++ 操作,num++ 是 num=num+1; 不是一个原子操作

package com.example.demo.thread;

public class VolatileAtomicTest {
    private static int num = 0;

    public static void increase(){
        num ++;
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j <1000 ; j++) {
                        increase();
                    }
                }
            });
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }
        System.out.println(num);
    }
}

多次运行结果:

num结果出现不一致,说明volatile不具有原子性

posted @ 2020-05-05 18:58  小污龟  阅读(358)  评论(0编辑  收藏  举报