在Java實現的併發隊列中, 實際上內部實現都使用了AtomicInteger爲隊列在高併發環境下計數的. java
下面是一段AtomicInteger.getAndDecrement的方法源碼片斷:
/** 算法
* Atomically decrements by one the current value. * * @return the previous value */ public final int getAndDecrement() { for (;;) { //獲取當前值 int current = get(); //設置修改後的值 int next = current - 1; //compareAndSet: cas方法 if (compareAndSet(current, next)) //只有在正確修改值後,才返回. return current; } }
compareAndSet則調用了unsafe.compareAndSwapInt(this, valueOffset, expect, update); 安全
/** * Atomically update Java variable to <tt>x</tt> if it is currently * holding <tt>expected</tt>. * @return <tt>true</tt> if successful */ public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
因此最終還須要native方法的實現(即虛擬機JVM), 以後我想JVM再去CPU發送CAS操做指令. 併發
CAS算法:compareAndSet的簡寫, 即比較再設值. 高併發