java中關於AtomicInteger的使用


在Java語言中,++i和i++操作並不是線程安全的,在使用的時候,不可避免的會用到synchronized關鍵字。而AtomicInteger則通過一種線程安全的加減操作接口。咳喲參考我之前寫的一篇博客http://www.cnblogs.com/sharkli/p/5597148.html,今天偶然發現可以不用synchronized使用AtomicInteger完成同樣的功能,具體代碼如下,

package TestAtomicInteger;

import java.util.concurrent.atomic.AtomicInteger;

class MyThread implements Runnable {
//    static  int i = 0;
	 static AtomicInteger ai=new AtomicInteger(0);
	 

    public void run() {
        for (int m = 0; m < 1000000; m++) {
        	ai.getAndIncrement();
        }
    }
};

public class TestAtomicInteger {
    public static void main(String[] args) throws InterruptedException {
        MyThread mt = new MyThread();

        Thread t1 = new Thread(mt);
        Thread t2 = new Thread(mt);
        t1.start();
        t2.start();
        Thread.sleep(500);
        System.out.println(MyThread.ai.get());
    }
}

  可以發現結果都是2000000,也就是說AtomicInteger是線程安全的。

值得一看。

這里,我們來看看AtomicInteger是如何使用非阻塞算法來實現並發控制的。

AtomicInteger的關鍵域只有一下3個:

 

Java代碼   收藏代碼
  1. // setup to use Unsafe.compareAndSwapInt for updates  
  2. private static final Unsafe unsafe = Unsafe.getUnsafe();  
  3. private static final long valueOffset;  
  4. private volatile int value;  

 這里, unsafe是java提供的獲得對對象內存地址訪問的類,注釋已經清楚的寫出了,它的作用就是在更新操作時提供“比較並替換”的作用。實際上就是AtomicInteger中的一個工具。

valueOffset是用來記錄value本身在內存的編譯地址的,這個記錄,也主要是為了在更新操作在內存中找到value的位置,方便比較。

注意:value是用來存儲整數的時間變量,這里被聲明為volatile,就是為了保證在更新操作時,當前線程可以拿到value最新的值(並發環境下,value可能已經被其他線程更新了)。

這里,我們以自增的代碼為例,可以看到這個並發控制的核心算法:

 

/**
* 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;
}
}

public final boolean compareAndSet(int expect, int update) {
//使用unsafe的native方法,實現高效的硬件級別CAS
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}

 

 好了,看到這個代碼,基本上就看到這個類的核心了。相對來說,其實這個類還是比較簡單的。可以參考http://hittyt.iteye.com/blog/1130990


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM