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不具有原子性