今天测试了多线程并发计数的性能:结果测试性能为:
计数类型 | 运行时间 | 执行结果 | |
同步 | 478 | 10000000 | |
lock | 434 | 10000000 | |
AtomicInteger | 739 | 10000000 | |
none | 417 | 错误 |
测试结果显示原子操作性能还是比较的差;
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantLock; public class Counter { private AtomicInteger atomicI = new AtomicInteger(0); ReentrantLock lock = new ReentrantLock(); private int m = 0; private int k = 0; private int l = 0; public static void main(String[] args) { atomic(1); atomic(2); atomic(3); atomic(4); } public static void atomic(final int type){ final Counter cas = new Counter(); List<Thread> ts = new ArrayList<Thread>(600); long start = System.currentTimeMillis(); for (int j = 0; j < 10000; j++) { Thread t = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 1000; i++) { //cas.count(); if(type==1){ cas.safeCount(); }else if(type==2){ cas.count2(); }else if(type==3){ cas.count(); }else if(type==4){ cas.count1(); } //cas.count1(); } } }); ts.add(t); } for (Thread t : ts) { t.start(); } // 等待所有线程执行完成 for (Thread t : ts) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } if(type==1){ System.out.println(type +"automic操作"+cas.atomicI.get()); }else if(type==2){ System.out.println(type +"lock:操作"+cas.m); }else if(type==3){ System.out.println(type +"synchronized:操作"+cas.k); }else if(type==4){ System.out.println(type +"none:操作"+cas.l); } System.out.println(System.currentTimeMillis() - start); } /** * 使用CAS实现线程安全计数器 */ private void safeCount() { atomicI.incrementAndGet(); } /** * 非线程安全计数器 存在竞争争条件,所以计算有错误 */ private void count1() { l++; } /** * 同步线程安全计数器 */ private synchronized void count() { k++; } /** * 锁线程安全计数器 */ private void count2() { //如果不加锁会计算出问题 lock.lock(); try{ m++; }catch(Exception e ){ }finally{ lock.unlock(); } } }