在经历了以下问题之后,
同步块可以比 Atomics 更快吗?,
我写了一个简单的程序来比较AtomicInteger和同步块的性能差异(在里面递增int)。每次我运行这个程序时,它给我的比率 > 100。我的笔记本电脑有 Intel Corei3,下面的行打印 4。
System.out.println(Runtime.getRuntime().availableProcessors())
当我使用
THREAD_COUNT = 1;
这个比率是最低的。它在 100 左右变化。对于
THREAD_COUNT = 10;
比例在800左右。
问题1:你能告诉我这是测试AtomicInteger VS同步增量()方法性能差异的正确方法吗?
问题2:如果我增加THREAD_COUNT
,比率增加,为什么?我认为这是因为更多的线程在同步语句中被阻塞并且需要更多的 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);
}
}
}