詳解Java并發(fā)編程之原子類
原子數組
原子數組有AtomicIntegerArray
、AtomicLongArray
、AtomicReferenceArray
,主要是用來對數組中的某個元素進行原子操作。三個類的方法基本類似,這里只介紹一下AtomicIntegerArray
的方法。
AtomicIntegerArray
兩個構造方法,第一個構造方法傳入數組長度初始化一個所有值都為0
的數組,第二個構造方法直接傳入一個數組來進行初始化。
public AtomicIntegerArray(int length) public AtomicIntegerArray(int[] array)
先獲取數組中索引為i
的值,然后對它進行加1
public final int getAndIncrement(int i)
先獲取數組中索引為i
的值,然后對它進行減1
public final int getAndDecrement(int i)
先對數組中索引為i
的值進行加1
,然后獲取新值
public final int incrementAndGet(int i)
先對數組中索引為i的值進行減1,然后獲取新值
public final int decrementAndGet(int i)
先對數組中索引為i
的值進行加delta
,然后獲取新值
public final int addAndGet(int i, int delta)
先獲取數組中索引為i的值,然后對它進行加delta
public final int getAndAdd(int i, int delta)
先獲取數組中索引為i
的值,然后把它設置為newValue
public final int getAndSet(int i, int newValue)
先獲取數組中索引為i
的值,然后執(zhí)行指定的操作對其進行更新
public final int getAndUpdate(int i, IntUnaryOperator updateFunction)
先執(zhí)行指定的操作對其進行更新,然后獲取新值
public final int updateAndGet(int i, IntUnaryOperator updateFunction)
原子更新器
原子更新器有AtomicIntegerFieldUpdater
、AtomicLongFieldUpdater
、AtomicReferenceFieldUpdater
,它們的作用是對某個對象的某個屬性進行原子操作,同樣三個類的操作基本相同,只是屬性的類型不同而已,這里以AtomicIntegerFieldUpdater
為例介紹基本方法。
AtomicIntegerFieldUpdater
類中提供了一個靜態(tài)方法來創(chuàng)建對象,兩個參數分別是tclass
:要操作的類,fieldName
:要操作的類的屬性名
public static <U> AtomicIntegerFieldUpdater<U> newUpdater(Class<U> tclass, String fieldName)
先獲取對象obj
的屬性fieldName
的值,然后對其進行自增1
操作
public int getAndIncrement(T obj)
先獲取對象obj
的屬性fieldName
的值,然后對其進行自減1
操作
public int getAndDecrement(T obj)
先把對象obj
的屬性fieldName
的值進行自增1
,然后獲取新值
public int incrementAndGet(T obj)
先把對象obj
的屬性fieldName
的值進行自減1
,然后獲取新值
public int decrementAndGet(T obj)
先獲取對象obj
的屬性fieldName
的值,然后對其加delta
public int getAndAdd(T obj, int delta)
先把對象obj
的屬性fieldName
的值加delta
,然后獲取新值
public int addAndGet(T obj, int delta)
先獲取對象obj
的屬性fieldName
的值,然后把它的值設為newValue
public int getAndSet(T obj, int newValue)
先獲取對象obj
的屬性fieldName
的值,然后執(zhí)行指定的操作把更新它的值
public final int getAndUpdate(T obj, IntUnaryOperator updateFunction)
原子累加器
原子累加器LongAdder
是jdk1.8
新增的一個類,它的作用和AtomicInteger
、AtomicLong
類似,但是在多線程情況下它的性能要高很多,原因是LongAdder
維護了一個Cell
數組,累加操作時每個線程對其中一個數據進行操作,最后再把結果進行匯總,提高了并發(fā)性。
LongAdder
無參構造方法什么也沒有做,默認累加器的結果就是0
public LongAdder()
sum
方法就是對Cell
數組中各單元的值進行求和,然后返回當前累加器的值
public long sum()
累加器自增1
public void increment()
累加器自減1
public void decrement()
累加器加x
public void add(long x)
累加器的值重置為0
public void reset()
先獲取累加器的值,然后再重置為0
public long sumThenReset()
以上就是詳解Java并發(fā)編程之原子類的詳細內容,更多關于Java并發(fā)原子類的資料請關注腳本之家其它相關文章!
相關文章
如何在SpringBoot 中使用 Druid 數據庫連接池
這篇文章主要介紹了SpringBoot 中使用 Druid 數據庫連接池的實現步驟,幫助大家更好的理解和學習使用SpringBoot,感興趣的朋友可以了解下2021-03-03解決idea出現的java.lang.OutOfMemoryError:?Java?heap?space的問題
我們在使用idea的時候經常會遇到一些問題,本文介紹了如何解決idea出現的java.lang.OutOfMemoryError:?Java?heap?space的問題,文中有相關的圖文示例,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06