volatile没有原子性
volatile的变量复合操作不具有原子性:比如i++;
案例
用synchronized:
class MyNumber{ int number; public synchronized void addplus(){ number++; } } public class VolatileNoAtomicDemo { public static void main(String[] args) { MyNumber mynumber = new MyNumber(); for(int i = 1;i<=10;i++){ new Thread(()->{ for (int j = 1; j <= 1000; j++) { mynumber.addplus(); } },String.valueOf(i)).start(); } //暂停2秒中 try{ TimeUnit.SECONDS.sleep(2);}catch(InterruptedException e) {e.printStackTrace();} System.out.println(mynumber.number); } } 运行结果: 10000
用volatile
class MyNumber{ volatile int number; public void addplus(){ number++; } } public class VolatileNoAtomicDemo { public static void main(String[] args) { MyNumber mynumber = new MyNumber(); for(int i = 1;i<=10;i++){ new Thread(()->{ for (int j = 1; j <= 1000; j++) { mynumber.addplus(); } },String.valueOf(i)).start(); } //暂停2秒中 try{ TimeUnit.SECONDS.sleep(2);}catch(InterruptedException e) {e.printStackTrace();} System.out.println(mynumber.number); } } 结果为: 9445 不是10000;
原因:number++实际上三个步骤