测试表明上述对于300个线程,每个线程做10000次加1操作,内置锁syncronized比atomicInteger效率要高
测试代码如下:
public class SyncWithAtomicTest {
private int count=0;
private static final int threadCount=300;
private static final int countNum=10000;
private final AtomicInteger countAtomicInteger=new AtomicInteger(0);
private static final ExecutorService threadPool=Executors.newFixedThreadPool(threadCount);
private final CountDownLatch latchStart=new CountDownLatch(threadCount);
private final CountDownLatch latchEnd=new CountDownLatch(threadCount);
public synchronized void addWithCountSync(){
for(int i=0;i<countNum;i++){
count++;
}
}
public void addWithAtomicCount(){
for(int i=0;i<countNum;i++){
countAtomicInteger.incrementAndGet();
}
}
public static void main(String[] args) throws InterruptedException {
SyncWithAtomicTest obj=new SyncWithAtomicTest();
Long oldTime=System.currentTimeMillis();
for(int i=0;i<threadCount;i++){
CountTask t=new CountTask();
t.setTarget(obj);
threadPool.execute(t);
}
obj.latchEnd.await();
Long endTime=System.currentTimeMillis()-oldTime;
// System.out.println("===============atomic all finish,cost:"+endTime+",the res:"+obj.countAtomicInteger.get());
System.out.println("===============sync all finish,cost:"+endTime+",the res:"+obj.count);
}
static class CountTask implements Runnable{
private SyncWithAtomicTest target;
public void run() {
try {
target.latchStart.countDown();
target.latchStart.await();
//we do add oper when all threads is ready
target.addWithCountSync();
// target.addWithAtomicCount();
System.out.println("thread:"+Thread.currentThread().getId()+",finish the work");
target.latchEnd.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
public void setTarget(SyncWithAtomicTest target) {
this.target = target;
}
}
}原文:http://blog.csdn.net/zhaozhenzuo/article/details/36622351