Skip to main content

从数字递增看锁与无锁

huhxAbout 1 minjavaConcurrency-CasConcurrency

测试用例

sync-1
public class IncrementMain {
    private final static int concurrency = 1000;
    private final static int times = 100000;
    private static volatile int count = 0;

    public static void main(String[] args) throws InterruptedException {
        var threads = new Thread[concurrency];

        for (int i = 0; i < concurrency; i++) {
            threads[i] = new Thread(() -> {
                for (int j = 0; j < times; j++) {
                    synchronized (IncrementMain.class) {
                        count++;
                    }
                }
            });
        }

        long start = System.currentTimeMillis();

        for (Thread thread : threads) thread.start();
        for (Thread thread : threads) thread.join();

        long end = System.currentTimeMillis();

        System.out.printf("result: %d, time: %d", count, end - start);
    }
}

输出结果如下:

并发量循环次数细粒度synchronized粗粒度synchronizedAtomicIntegerLongAdder
10100000000662606152212641374
100100000000522815561225621211
100010000034845141827147
10000100663497488511

关于synchronizedReentrantLock的比较,可以参考:

分析

总结

FAQ

参考