程式碼中 volatile int num 僅保證可見性,不保證原子性。num++ 包含讀取、遞增、寫入三步驟,兩執行緒可能同時讀取舊值 0,各自遞增寫入 1,導致輸出 1,1。解決方法:
synchronized 同步區塊:synchronized(this) { num++; }AtomicInteger:AtomicInteger num = new AtomicInteger(); num.incrementAndGet();volatile 適用於單一寫入、多讀取的旗標變數,不適用於複合操作。