AtomicInteger類的理解與使用
參考:
- 定義:AtomicInteger是一個提供原子操作的Integer類,通過線程安全的方式操作加減。
- 使用場景 :適合高並發情況下的使用
AtomicInteger是在使用非阻塞算法實現並發控制,在一些高並發程序中非常適合,但並不能每一種場景都適合,不同場景要使用使用不同的數值類。
注意:高並發的情況下,
i++
無法保證原子性,往往會出現問題,所以引入AtomicInteger
類。 - 部分源碼:
public class AtomicInteger extends Number implements java.io.Serializable {
private static final long serialVersionUID = 6214790243416807050L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
里value使用了volatile關鍵字,volatile在這里可以做到的作用是使得多個線程可以共享變量,但是問題在於使用volatile將使得VM優化失去作用,導致效率較低,所以要在必要的時候使用,因此AtomicInteger類不要隨意使用,要在使用場景(高並發/多線程)下使用。
對於全局變量的數值類型操作(比如多線程) num++,若沒有加synchronized關鍵字則是線程不安全的.
例如:
public class AtomicIntegerTest1 {
public static int count=0;
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
new Thread(){
@Override
public void run() {
count++;
}
}.start();
}
System.out.println("count: "+count);
}
}
輸出: count: 8947
明顯數值錯誤,線程不安全
若是使用volatile
public class AtomicIntegerTest1 {
static volatile int count=0;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
new Thread(){
@Override
public void run() {
count++;
}
}.start();
}
// Thread.sleep(1000);
System.out.println("count: "+count);
}
}
輸出:count: 61
volatile僅僅保證變量在線程間保持可見性,卻依然不能保證非原子性的操作。
使用AtomicInteger
public class AtomicIntegerTest1 {
static AtomicInteger count=new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
new Thread(){
@Override
public void run() {
count.getAndIncrement();
}
}.start();
}
// Thread.sleep(1000);
System.out.println("count: "+count);
}
}
輸出:count: 59
方法
方法 | 定義 |
---|---|
AtomicInteger() |
創建一個新的AtomicInteger,初始值為 0 。 |
AtomicInteger (int initialValue) |
用給定的初始值創建一個新的AtomicInteger |
int get () |
獲取當前值 |
set (int newValue) |
設置指定值: set()會立刻修改舊值,別的線程可以立刻看到更新后的值 |
void lazySet (int newValue) |
設置指定值:lazySet不會立刻(但是最終會)修改舊值,別的線程看到新值的時間會延遲一些 |
int getAndSet (int newValue) |
設置指定值並返回原來的值 |
boolean compareAndSet (int expect, int update) |
如果當前值等於入參expect,則把值設為update,並返回ture,如果不等則返回false |
weakCompareAndSet (int expect, int update) |
jdk1.9之前,與compareAndSet完全一致; 1.9中: weakCompareAndSet有可能不是原子的去更新值,這取決於虛擬機的實現(效率高) |
int getAndIncrement () |
i++ |
int getAndDecrement () |
i-- |
int getAndAdd (int delta) |
當前值加上delta,返回以前的值 |
int incrementAndGet () |
++i |
int decrementAndGet () |
--i |
addAndGet (int delta) |
當前值加上delta,返回新的值 |
int getAndUpdate (IntUnaryOperator updateFunction) |
使用IntBinaryOperator 對當前值進行計算,並更新當前值,返回計算前的舊值 (比如:Math::max ) |
int updateAndGet (IntUnaryOperator updateFunction) |
使用IntBinaryOperator 對當前值進行計算,並更新當前值,返回計算后的新值 |
int getAndAccumulate (int x, IntBinaryOperator accumulatorFunction) |
使用IntBinaryOperator 對當前值和x進行計算,並更新當前值,返回計算前的舊值 |
int accumulateAndGet (int x, IntBinaryOperator accumulatorFunction) |
使用IntBinaryOperator 對當前值和x進行計算,並更新當前值,返回計算后的新值 |
/**
* 演示AtomicInteger中1.8新增方法的使用方法
*/
@Test
public void operatorTest(){
AtomicInteger i = new AtomicInteger(0);
//lambda表達式中參數operand表示AtomicInteger的當前值
int andUpdate = i.getAndUpdate(operand -> ++operand);
System.out.println(andUpdate); //result: 0
System.out.println(i.get()); //result: 1
int i1 = i.updateAndGet(operand -> operand-2 );
System.out.println(i1); //result: -1
System.out.println(i.get()); //result: -1
//lambda表達式中參數left表示AtomicInteger的當前值、right表示前面那個參數5
int andAccumulate = i.getAndAccumulate(5, (left, right) -> left + right);
System.out.println(andAccumulate); //result: -1
System.out.println(i.get()); //result: 4
int i2 = i.accumulateAndGet(4, (left, right) -> left + right);
System.out.println(i2); //result: 8
System.out.println(i.get()); //result: 8
}
案例
- 使用案例1:
public class AtomicTest {
static long randomTime() {
return (long) (Math.random() * 1000);
}
public static void main(String[] args) {
// 阻塞隊列,能容納100個文件
final BlockingQueue<Filequeue = new LinkedBlockingQueue<File>(100);
// 線程池
final ExecutorService exec = Executors.newFixedThreadPool(5);
final File root = new File("D:\\ISO");
// 完成標志
final File exitFile = new File("");
// 原子整型,讀個數
// AtomicInteger可以在並發情況下達到原子化更新,避免使用了synchronized,而且性能非常高。
final AtomicInteger rc = new AtomicInteger();
// 原子整型,寫個數
final AtomicInteger wc = new AtomicInteger();
// 讀線程
Runnable read = new Runnable() {
public void run() {
scanFile(root);
scanFile(exitFile);
}
public void scanFile(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory() || pathname.getPath().endsWith(".iso");
}
});
for (File one : files)
scanFile(one);
} else {
try {
// 原子整型的incrementAndGet方法,以原子方式將當前值加 1,返回更新的值
int index = rc.incrementAndGet();
System.out.println("Read0: " + index + " " + file.getPath());
// 添加到阻塞隊列中
queue.put(file);
} catch (InterruptedException e) {
}
}
}
};
// submit方法提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。
exec.submit(read);
// 四個寫線程
for (int index = 0; index < 4; index++) {
// write thread
final int num = index;
Runnable write = new Runnable() {
String threadName = "Write" + num;
public void run() {
while (true) {
try {
Thread.sleep(randomTime());
// 原子整型的incrementAndGet方法,以原子方式將當前值加 1,返回更新的值
int index = wc.incrementAndGet();
// 獲取並移除此隊列的頭部,在元素變得可用之前一直等待(如果有必要)。
File file = queue.take();
// 隊列已經無對象
if (file == exitFile) {
// 再次添加"標志",以讓其他線程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + ": " + index + " " + file.getPath());
} catch (InterruptedException e) {
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}
- 使用案例2:
public class TestAtomicInteger {
private static final int THREADS_COUNT = 2;
public static int count = 0;
public static volatile int countVolatile = 0;
public static AtomicInteger atomicInteger = new AtomicInteger(0);
public static CountDownLatch countDownLatch = new CountDownLatch(2);
public static void increase() {
count++;
countVolatile++;
atomicInteger.incrementAndGet();
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[THREADS_COUNT];
for(int i = 0; i< threads.length; i++) {
threads[i] = new Thread(() -> {
for(int i1 = 0; i1 < 1000; i1++) {
increase();
}
countDownLatch.countDown();
});
threads[i].start();
}
countDownLatch.await();
System.out.println(count);
System.out.println(countVolatile);
System.out.println(atomicInteger.get());
}
}