谈谈原子变量与锁的性能比较

正常状况下基于原子变量实现的效率会比基于锁的效率高效,由于基于锁的时候会发生线程间的上下文切换,而原子变量不会。用程序实际测试了一下也确实如此,结论是原子变量的平均效率是锁效率的3倍左右,代码以下:java

public class CasAndLockTest {编程

    public static void main(String[] args) {
        LockInteger li = new LockInteger(0);
        AtomicInteger ai = new AtomicInteger(0);
        for (int k = 0; k < 1; k++) {
            new Thread() {
                public void run() {
                    long start = System.currentTimeMillis();
                    for (int i = 0; i < 10000000; i++) {
                        li.incrementAndGet();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("LockInteger 耗时: " + (end - start));
                }
            }.start();
        }
        for (int k = 0; k < 1; k++) {
            new Thread() {
                public void run() {
                    long start = System.currentTimeMillis();
                    for (int i = 0; i < 10000000; i++) {
                        ai.incrementAndGet();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("AtomicInteger 耗时: " + (end - start));
                }
            }.start();
        }
    }并发

    private static class LockInteger {
        private int val;性能

        public LockInteger(int val) {
            this.val = val;
        }测试

        public synchronized int incrementAndGet() {
            return ++val;
        }
    }this

}线程

有兴趣的能够本身更改迭代次数k进行测试。但从“java并发编程实战”中得知:当线程之间高度竞争的时候,锁的性能会比原子变量高。而实际状况是还没测出来,其实缘由比较好理解:锁在高度竞争时会不断挂起恢复线程从而让出cpu使用权给其他的计算资源,原子变量在高度竞争时会一直占用cpu所以其他的计算资源因饥饿致使变慢。资源

相关文章
相关标签/搜索