您的位置:首页 > 其它

volatile、非volatile、Atomic计数器比较

2016-04-11 15:56 253 查看
import java.util.concurrent.atomic.AtomicInteger;

public class Atomicity {
private static volatile int nonAtomicCounter = 0;
private static long nonVolNonAtomicCountter = 0;
private static volatile AtomicInteger atomicCounter = new AtomicInteger(0);
private static int times = 0;

//对单个的普通 变量的写用同一个监视器同步
public static synchronized void set(long l) {
nonVolNonAtomicCountter = l;
}

//对单个的普通变量的读用同一个监视器同步
public static synchronized long get() {
return nonVolNonAtomicCountter;
}

public static void getAndIncrement () { //普通方法调用
long temp = get();           //调用已同步的读方法
temp += 1L;                  //普通写操作
set(temp);                   //调用已同步的写方法
}

public static void caculate() {
times++;
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
getAndIncrement();
nonAtomicCounter++;
atomicCounter.incrementAndGet();
}
}).start();
}

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}

public static void main(String[] args) {
caculate();
while (nonVolNonAtomicCountter == 1000) {
nonAtomicCounter = 0;
atomicCounter.set(0);
set(0);
caculate();
}

System.out.println("nonVolNonAtomicCountter: " + times + ":"
+ nonVolNonAtomicCountter);
System.out.println("Non-atomic counter: " + times + ":"
+ nonAtomicCounter);
System.out.println("Atomic counter: " + times + ":" + atomicCounter);
}
}

result :

nonVolNonAtomicCountter: 16:999

Non-atomic counter: 16:1000

Atomic counter: 16:1000

所以:volatile和加监视器都不能实现原子操作。volatile仅能保证从主内存读到线程内存是最新的值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: