标签:volatile atomicinteger 原子性 一致性 synchronized
今天在网上看到一篇文章,谈论的是根据volatile特性来用1000个线程不断的累加数字,每次累加1个,到最后值确不是1000.
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Counter {
public static AtomicInteger count = new AtomicInteger();//原子操作
public static CountDownLatch latch= new CountDownLatch(1000);//线程协作处理
public static volatile int countNum = 0;//volatile 只能保证可见性,不能保证原子性
public static int synNum = 0;//同步处理计算
public static void inc() {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
countNum++;
int c = count.addAndGet(1);
add();
System.out.println(Thread.currentThread().getName() + "------>" + c);
}
public static synchronized void add(){
synNum++;
}
public static void main(String[] args) {
//同时启动1000个线程,去进行i++计算,看看实际结果
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.inc();
latch.countDown();
}
},"thread" + i).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
System.out.println("运行结果:Counter.count=" + count.get() + ",,," + countNum + ",,," + synNum);
}
volatile、synchronized、AtomicInteger多线程累加1000个计数的区别
标签:volatile atomicinteger 原子性 一致性 synchronized
原文地址:http://blog.csdn.net/a_yyc1990/article/details/41478639