標籤:java 多線程
(一)Atomic的使用
java.util.concurrent中提供了atomic原子包,可以實現原子操作(atomic operation),即在多線程環境中,執行的操作不會被其他線程打斷。
/** * atomic簡單demo * * @author peter_wang * @create-time 2014-6-9 上午9:29:58 */public class AtomicDemo extends Thread { private static final AtomicInteger TEST_INT = new AtomicInteger(); @Override public void run() { TEST_INT.incrementAndGet(); } /** * @param args */ public static void main(String[] args) { for (int i = 0; i < 1000; i++) { AtomicDemo demo = new AtomicDemo(); demo.start(); try { demo.join(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("最終結果:"+TEST_INT); }}
運行結果:
最終結果:1000
多個線程對AtomicInteger類型的變數進行自增操作,運算結果無誤。若用普通的int變數,i++多線程操作可能導致結果有誤。
(二)原理分析
源碼分析:
incrementAndGet函數
/** * Atomically increments by one the current value. * * @return the updated value */ public final int incrementAndGet() { for (;;) { //擷取當前值value int current = get(); int next = current + 1; //迴圈執行到遞增成功 if (compareAndSet(current, next)) return next; } }
private volatile int value;
value是volatile類型,確保此線程能擷取到最新值。
方法不斷擷取value值再進行遞增操作,直至操作成功。
public final boolean compareAndSet(int expect, int update) {return unsafe.compareAndSwapInt(this, valueOffset, expect, update); }compareAndSet使用Unsafe調用native本地方法CAS(CompareAndSet)遞增數值。
(三)CAS簡要
CAS利用CPU調用底層指令實現。
單一處理器,進行簡單的讀寫操作時,能保證自身讀取的原子性,多處理器或複雜的記憶體操作時,CAS採用匯流排加鎖或緩衝加鎖方式保證原子性。
1.匯流排加鎖
如i=0初始化,多處理器多線程環境下進行i++操作下,處理器A和B同時讀取i值到各自緩衝,分別進行遞增,回寫值i=1相同。處理器提供LOCK#訊號,進行匯流排加鎖後,處理器A讀取i值並遞增,處理器B被阻塞不能讀取i值。
2.緩衝加鎖
匯流排加鎖,在LOCK#訊號下,其他線程無法操作記憶體,效能較差,緩衝加鎖能較好處理該問題。
緩衝加鎖,處理器A和B同時讀取i值到緩衝,處理器A提前完成遞增,資料立即回寫到主記憶體,並讓處理器B緩衝該資料失效,處理器B需重新讀取i值。
java-多線程深入(五)Atomic分析