【實戰Java高併發程序設計 4】數組也能無鎖:AtomicIntegerArray

  除了提供基本數據類型外,JDK還爲咱們準備了數組等複合結構。當前可用的原子數組有:AtomicIntegerArray、AtomicLongArray和AtomicReferenceArray,分別表示整數數組、long型數組和普通的對象數組。java

   這裏以AtomicIntegerArray爲例,展現原子數組的使用方式。數組

AtomicIntegerArray本質上是對int[]類型的封裝。使用Unsafe類經過CAS的方式控制int[]在多線程下的安全性。它提供瞭如下幾個核心API:  
//得到數組第i個下標的元素  
public final int get(int i)  
//得到數組的長度  
public final int length()  
//將數組第i個下標設置爲newValue,並返回舊的值  
public final int getAndSet(int i, int newValue)  
//進行CAS操做,若是第i個下標的元素等於expect,則設置爲update,設置成功返回true  
public final boolean compareAndSet(int i, int expect, intupdate)  
//將第i個下標的元素加1  
public final int getAndIncrement(int i)  
//將第i個下標的元素減1  
public final int getAndDecrement(int i)  
//將第i個下標的元素增長delta(delta能夠是負數)  
public final int getAndAdd(int i, int delta)  

 

 下面給出一個簡單的示例,展現AtomicIntegerArray使用:安全

01 public class AtomicIntegerArrayDemo {  
02    staticAtomicIntegerArray arr = new AtomicIntegerArray(10);  
03     public staticclass AddThread implements Runnable{  
04         publicvoid run(){  
05            for(intk=0;k<10000;k++)  
06                 arr.getAndIncrement(k%arr.length());  
07         }  
08     }  
09    public staticvoid main(String[] args) throws InterruptedException {  
10         Thread[]ts=new Thread[10];  
11         for(intk=0;k<10;k++){  
12            ts[k]=new Thread(new AddThread());  
13         }  
14         for(intk=0;k<10;k++){ts[k].start();}  
15         for(intk=0;k<10;k++){ts[k].join();}  
16         System.out.println(arr);  
17    }  
18 }  

 

上述代碼第2行,申明瞭一個內含10個元素的數組。第3行定義的線程對數組內10個元素進行累加操做,每一個元素各加1000次。第11行,開啓10個這樣的線程。所以,能夠預測,若是線程安全,數組內10個元素的值必然都是10000。反之,若是線程不安全,則部分或者所有數值會小於10000。多線程

程序的輸出結果以下:併發

  1. [10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000,10000, 10000]  


這說明AtomicIntegerArray確實合理地保證了數組的線程安全性。高併發

  

 

 

摘自:實戰Java高併發程序設計spa

相關文章
相關標籤/搜索