Java併發程式設計的藝術之七----原子更新基本型別
1.原子更新基本型別
·AtomicBoolean:原子更新布林型別。
·AtomicInteger:原子更新整型。
·AtomicLong:原子更新長整型
·int addAndGet(int delta):以原子方式將輸入的數值與例項中的值(AtomicInteger裡的value)相加,並返回結果。
·boolean compareAndSet(int expect,int update):如果輸入的數值等於預期值,則以原子方式將該值設定為輸入的值。
·int getAndIncrement():以原子方式將當前值加1,注意,這裡返回的是自增前的值。
·void lazySet(int newValue):最終會設定成newValue
·int getAndSet(int newValue):以原子方式設定為newValue的值,並返回舊值。
getAndIncrement是如何實現原子操作的呢?
public final int getAndIncrement() { for (;;) { int int next = current + 1; if (compareAndSet(current, next)) return } } public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update); } |
無限迴圈第一步先取得atomicInteger儲存的數值,,第二步對atomicInteger的當前數值進行加1操作,,關鍵的第三步呼叫compareAndSet方法來進行原子更新操作,該方法先通過this和valueoffset計算出當前的值的大小,然後except是傳入的current的值,比較計算出的值和expect的值是否相等,,相等意味著atomicInteger的值沒有被其他執行緒修改過,則將atomicInteger的當前數值更新成next的值,如果不等compareAndSet方法會返回false,程式進行for迴圈重新進行compareAndSet操作。
2.原子更新陣列
陣列value通過構造方法傳遞進去,然後AtomicIntegerArray會將當前陣列複製一份,所以當AtomicIntegerArray對內部的陣列元素進行修改時,不會影響傳入的陣列