標籤:
先參考一個例子 http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html#!comments
即使只是i++,實際上也是由多個原子操作組成:read i; inc; write i,假如多個線程同時執行i++,volatile只能保證他們操作的i是同一塊記憶體,但依然可能出現寫入髒資料的情況。如果配合Java 5增加的atomic wrapper classes,對它們的increase之類的操作就不需要sychronized。
使用AtomicInteger,它封裝了一些integer的原子操作,並使之安全執行緒
package threadTest;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;public class AtomicIntegerTestApp1 { public static AtomicInteger count = new AtomicInteger(0); public static void inc() {// count++; count.incrementAndGet(); } public static void main(String[] args) throws InterruptedException { ExecutorService service= Executors.newFixedThreadPool(Integer.MAX_VALUE); for (int i = 0; i < 10000; i++) { service.execute(new Runnable() { @Override public void run() { ThreadPoolTestApp1.inc(); } }); } service.shutdown(); //給予一個關閉時間(timeout),但是實際關閉時間應該會這個小 service.awaitTermination(300, TimeUnit.SECONDS); System.out.println("運行結果:Counter.count=" + ThreadPoolTestApp1.count); }}
Java中的原子操作包括:
1)除long和double之外的基本類型的賦值操作
2)所有引用reference的賦值操作
3)java.concurrent.Atomic.* 包中所有類的一切操作
count++不是原子操作,是3個原子操作組合
1.讀取主存中的count值,賦值給一個局部成員變數tmp
2.tmp+1
3.將tmp賦值給count
安全執行緒的atomic wrapper classes例子