原文地址
先参考一个例子 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的原子操作,并使之线程安全
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);
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> inc() {
// count++;
count.incrementAndGet();
}
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> main(String[] args) <span style="color: #0000ff;">throws</span><span style="color: #000000;"> InterruptedException {
ExecutorService service</span>=<span style="color: #000000;"> Executors.newFixedThreadPool(Integer.MAX_VALUE);
</span><span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> i = 0; i < 10000; i++<span style="color: #000000;">) {
service.execute(</span><span style="color: #0000ff;">new</span><span style="color: #000000;"> Runnable() {
@Override
</span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> run() {
ThreadPoolTestApp1.inc();
}
});
}
service.shutdown();
</span><span style="color: #008000;">//</span><span style="color: #008000;">给予一个关闭时间(timeout),但是实际关闭时间应该会这个小</span>
service.awaitTermination(300<span style="color: #000000;">, TimeUnit.SECONDS);
System.out.println(</span>"运行结果:Counter.count=" +<span style="color: #000000;"> ThreadPoolTestApp1.count);
}
}
Java中的原子操作包括:
1)除long和double之外的基本类型的赋值操作
2)所有引用reference的赋值操作
3)java.concurrent.Atomic.* 包中所有类的一切操作
count++不是原子操作,是3个原子操作组合
1.读取主存中的count值,赋值给一个局部成员变量tmp
2.tmp+1
3.将tmp赋值给count