public class VolatileTest { private volatile int i = 0; public void add() { i++; } public int getI() { return this.i; } public static void main(String[] args) { final VolatileTest volatileTest = new VolatileTest(); for (int i = 0; i < 10000; i++) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep((int)Math.random() * 20); } catch (InterruptedException e) { e.printStackTrace(); } volatileTest.add(); } }).start(); } System.out.println(volatileTest.getI()); } }
read-update-write並非線程安全的java