1. 程式人生 > 其它 >Volatile不能保證原子性

Volatile不能保證原子性

  • 併發程式設計的三大特性 :可見性 原子性 有序性
  • volatile保證可見性和有序性,但不能保證原子性,保證原子性需要藉助synchronize這樣的鎖機制
    public class ThreadSychronizedTest {
    
        public static volatile  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() { public void run() { for (int j = 0; j <1000 ; j++) { increase(); } } }); threads[i] .start(); }
    //等待所有執行緒執行完 for (Thread t:threads) { t.join(); } //執行結果<=10000 System.out.println(num);//1000*10=10000? } }

    底層執行過程