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效率高很多