今天再看《Java并发编程实践》的时候提到了这样一句话:volatile关键字只能保证变量的可见性,无法保证变量的原子性。
当时没懂,搜了几个事例分析了一下,顺便也分析一下可以保证原子性的atom类的源码(这里以AtomInteger为例)
先看一下volatile无法保证原子性的事例:
class IntegerTestThread implements Runnable{
public void run() {
int x = 0;
while(x<1000){
atom.ai.addAndGet(1);
atom.integer++;
atom.i++;
x++;
}
atom.endThread.addAndGet(1);
}
}
public class atom {
public static AtomicInteger ai = new AtomicInteger();
public static volatile Integer integer = new Integer(0);
public static volatile int i = 0;
public static AtomicInteger endThread = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
new atom().testAtom();
}
public void testAtom() throws InterruptedException{
for(int i=0;i<100;i++){
new Thread