通過以下問題 Can synchronized blocks be faster than Atomics?,
我寫了一個簡單的程序來比較的AtomicInteger的性能差異和synchronized塊去後(裏面遞增INT)。我每次運行這個程序,它給了我比> 100 我的電腦有英特爾Corei3和下面的行打印4在Java中的AtomicInteger Vs的同步int變量:性能差異
System.out.println(Runtime.getRuntime().availableProcessors())
當我使用
THREAD_COUNT = 1;
的比例來最低。它改變周圍100。
THREAD_COUNT = 10;
的比例大約是800
問題1:你能告訴我這是測試的的性能差異的正確方法的AtomicInteger VS同步的增量( ) 方法?
問題2:如果我增加THREAD_COUNT
,比例增加,爲什麼?我認爲這是因爲更多線程在synchronized語句中被阻塞,並且需要更多的CPU任務。請給出意見。
package concurrent.atomic;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Performance {
private static final AtomicInteger atomicInt = new AtomicInteger(0);
private static volatile int counter = 0;
private static final Object LOCK = new Object();
private static final int THREAD_COUNT = 10;
public static void main(String[] args) {
System.out.println(Runtime.getRuntime().availableProcessors());
Runnable atomic = new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
int value = atomicInt.incrementAndGet();
//if (value % 1000 == 0)
//System.out.println("atomic value : "+value);
}
}
};
//System.out.println("1");
Runnable intCounter = new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
synchronized (LOCK) {
int value = ++counter;
//if (value % 1000 == 0)
//System.out.println("sync value "+value);
}
}
}
};
final ExecutorService atomicExecutor = Executors.newCachedThreadPool();
final ExecutorService primitiveExecutor = Executors.newCachedThreadPool();
for (int i = 0; i < THREAD_COUNT ; ++i) {
atomicExecutor.submit(atomic);
primitiveExecutor.submit(intCounter);
}
while (true) {
float ratio = (((float) (atomicInt.get() * 1.0))/counter) * 100;
System.out.println("ratio : " + ratio);
}
}
}
http://kennethxu.blogspot.in/2009/05/atomicinteger-vs-synchronized-monitor.html執行此操作。發現這個谷歌搜索。嘗試這個。 – 2013-04-11 12:55:44
這裏有個bug,你需要將'counter'聲明爲volatile。否則,不能保證主線程讀取最新值。 – 2013-04-11 14:16:45
是的..我需要改變我的代碼。 – HakunaMatata 2013-04-11 14:23:32