2019-07-22

2019-07-22  本文已影响0人  小程有话说

synchronized vs lock

中午闲来无事,比较了 synchronized lock 性能。

硬件: 2核4G
JDK: 1.8.0_212

测试在单线程、2线程、10线程、100线程下累加耗时。

synchronized code:

public class SyncTest {

    // 线程数,根据需求调整
    private static int threadNum = 2;

    private static int cycleNum = 1000000;

    public static void main(String[] args) throws InterruptedException {
        final Counter counter = new Counter();
        long startTime = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch(threadNum);
        for (int i = 0; i < threadNum; i++) {
            new Thread(() -> {
                for (int j = 0; j < cycleNum; j++) {
                    counter.add();
                }
                latch.countDown();
            }).start();
        }
        latch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("Spend time: " + (endTime - startTime));
    }

    static class Counter {

        private Object l = new Object();

        private long count;

        public void add() {
            synchronized (l) {
                count++;
            }
        }
    }
}

lock code:

public class LockTest {

    private static int threadNum = 1;

    private static int cycleNum = 1000000;

    public static void main(String[] args) throws InterruptedException {
        final Counter counter = new Counter();
        long startTime = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch(threadNum);
        for (int i = 0; i < threadNum; i++) {
            new Thread(() -> {
                for (int j = 0; j < cycleNum; j++) {
                    counter.add();
                }
                latch.countDown();
            }).start();
        }
        latch.await();
        long endTime = System.currentTimeMillis();
        System.out.println("Spend time: " + (endTime - startTime));
    }

    static class Counter {

        private Lock l = new ReentrantLock();

        private long count;

        public void add() {
            l.lock();
            try {
                count++;
            } finally {
                l.unlock();
            }
        }
    }
}

从耗时上来看,2者差别不大;但是lock相比synchronized提供了更多的功能。

上一篇下一篇

猜你喜欢

热点阅读