Java中CAS和synchronized多线程耗时对比测试

    科技2023-10-31  97

    设置线程数为1000个,选取操作为自增,代码如下

    package suanfa; import java.util.concurrent.atomic.AtomicInteger; public class Main { static AtomicInteger casCur = new AtomicInteger(0); static Integer syncCur = 0; public static void main(String[] args) { int threadSize = 1000; int maxCount = 2000000; casTest(threadSize, maxCount); syncTest(threadSize, maxCount); } public static void casTest(int size, int count) { long now = System.currentTimeMillis(); for (int i = 0; i < size; i++) { new Thread(()-> { while (casCur.get() < count) { casCur.getAndIncrement(); if (casCur.get() == count) { System.out.println("casTime:" + (System.currentTimeMillis() - now)); } } }).start(); } } public static void syncTest(int size, int count) { long now = System.currentTimeMillis(); for (int i = 0; i < size; i++) { new Thread(()-> { while (syncCur < count) { synchronized ("syncTest") { syncCur++; } if (syncCur == count) { System.out.println("syncTime:"+(System.currentTimeMillis()-now)); } } }).start(); } } }

    得到测试时间结果为: 有文章说如果线程竞争激烈,由于cas操作一直不成功,会出现耗时比synchronized慢的情况,本次测试是在6核12线程cpu中运行,得出结果应该是线程之间竞争不激烈导致

    增加线程数到10000个,得到结果与之前相差不大:

    线程数不变,自增阈值增加10倍,时间差别更明显:

    Processed: 0.016, SQL: 8