我已经读过很多文章,其中提到atomicinteger类比synchronize构造工作得更快。我在atomicinteger和synchronized上做了一些测试,在我的测试中,synchronized比atomicinteger快得多。我想了解出了什么问题:我的测试类不正确,或者atomicinteger在其他情况下工作得更快?
这是我的测试课:
public class Main {
public static void main(String[] args) throws InterruptedException
{
// creating tester "synchronized" class
TesterSynchronized testSyn = new TesterSynchronized();
// Creating 3 threads
Thread thread1 = new Thread(testSyn);
Thread thread2 = new Thread(testSyn);
Thread thread3 = new Thread(testSyn);
// start time
long beforeSyn = System.currentTimeMillis();
// start
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
long afterSyn = System.currentTimeMillis();
long delta = afterSyn - beforeSyn;
System.out.println("Test synchronized: " + delta + " ms");
// _______________________________________________________
// creating tester "atomicInteger" class
TesterAtomicInteger testAtomic = new TesterAtomicInteger();
thread1 = new Thread(testAtomic);
thread2 = new Thread(testAtomic);
thread3 = new Thread(testAtomic);
// start time
long beforeAtomic = System.currentTimeMillis();
// start
thread1.start();
thread2.start();
thread3.start();
thread1.join();
thread2.join();
thread3.join();
long afterAtomic = System.currentTimeMillis();
long deltaAtomic = afterAtomic - beforeAtomic;
System.out.println("Test atomic integer: " + deltaAtomic + " ms");
}
}
// Synchronized tester
class TesterSynchronized implements Runnable {
public int integerValue = 0;
public synchronized void run() {
for (int i = 0; i < 1_000_000; i++)
integerValue++;
}
}
// AtomicInteger class tester
class TesterAtomicInteger implements Runnable {
AtomicInteger atomicInteger = new AtomicInteger(0);
public void run() {
for (int i = 0; i < 1_000_000; i++)
atomicInteger.incrementAndGet();
}
}
测试参数:3线程,增量为1_000_000;结果:
测试同步:7毫秒。测试原子整数:51毫秒
我很高兴了解为什么会发生这种情况。
如果将同步方法更改为同步块,则测试将是正确的。
// Synchronized tester
class TesterSynchronized implements Runnable {
public int integerValue = 0;
public void run() {
for (int i = 0; i < 1_000_000; i++) {
synchronized (this) {
integerValue++;
}
}
}
}
1条答案
按热度按时间z3yyvxxp1#
代码中的明显区别是
AtomicIntger
版本允许线程的交叉存取,而synchronized
版本依次对每个线程执行整个循环。可能还有其他问题。例如,jvm可以合并对
synchronized
阻止。取决于平台,incrementAndGet
可能不是原子操作,而是作为cas循环实现的—如果争用很高,那可能是个问题(我对此不完全确定)。无论是哪种方式,如果有多个线程同时修改同一个内存位置,速度都不会很快。