AtomicInteger线程安全类 和 加了同步块的int类型进行递增耗时比较
模拟100个线程,每个线程内循环递增10000次
代码使用CountDownLatch做了线程阻塞等待,返回结果都是100万
电脑基本信息 我的电脑 联想 Lenovo G510 20238 笔记本电脑 操作系统 Windows 7 旗舰版 64位 SP1 主显卡 独立显卡(对游戏和电影支持较好) IE浏览器 版本号 8.0 基本硬件展示 处理器 英特尔 Core i5-4210M @ 2.60GHz 双核 主板 联想 00000000Not Defined 内存 4 GB ( 三星 DDR3L 1600MHz ) 主硬盘 西数 WDC WD5000LPCX-24C6HT0 ( 500 GB / 7200 转/分 ) 主显卡 ATI Radeon HD 8570M ( 联想 ) 显示器 奇美 CMO15A7 ( 15.7 英寸 ) 网卡 Atheros AR9485 Wireless Network Adapter / 联想 声卡 Conexant @ 英特尔 Haswell 高保真音频
AtomicInteger类代码
package com.thread.test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class ThreadTest003 { private static AtomicInteger ai = new AtomicInteger(0); public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(100); // TODO Auto-generated method stub ExecutorService es = Executors.newCachedThreadPool(); long begin = System.currentTimeMillis(); for(int i = 0; i < 100; i++){ es.execute(new Runnable() { @Override public void run() { for(int j = 0; j < 10000; j++){ ai.incrementAndGet(); } latch.countDown(); } }); } latch.await(); es.shutdown(); long end = System.currentTimeMillis(); System.out.println(ai.get() + " 耗时:" + (end - begin)); } }
效果
1000000 耗时:60
int类型代码
package com.thread.test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadTest004 { private static int k = 0; public static void main(String[] args) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(100); ExecutorService es = Executors.newCachedThreadPool(); long begin = System.currentTimeMillis(); for(int i = 0; i < 100; i++){ es.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub synchronized(ThreadTest003.class){ for(int j = 0; j < 10000; j++){ k++; } latch.countDown(); } } }); } latch.await(); es.shutdown(); long end = System.currentTimeMillis(); System.out.println(k + " 耗时:" + (end - begin)); } }
效果
1000000 耗时:8
耗时单位为毫秒,相比之下int 加了代码块同步比AtomicInteger效率高很多