java 锁性能对比

    @Test
    public void spec() {

        String [] titles = new String[]{"[no  sync]", "[  sync  ]", "[reenlock]"};
        long num = 10000, s = 0;
        for(int k = 0; k < 3; k++) {
            long start = System.currentTimeMillis();
            for (long i = 0; i < num; i++) {
                for (long j = 0; j < num; j++) {
                    if(k == 0) {
                        s += test1();
                    } else if(k == 1) {
                        s += test2();
                    } else if(k ==2) {
                        s += test3();
                    }
                }
            }
            long tick = System.currentTimeMillis() - start;
            System.out.println(String.format("times: %s %d %d", titles[k] , s , tick));
        }
    }

    public int test1() {
        int s = 0;
        s +=1 ;
        return s;
    }

    public synchronized int test2() {
        int s = 0;
        s +=1 ;
        return s;
    }

    private ReentrantLock lock = new ReentrantLock();
    public int test3() {
        try {
            lock.lock();
            int s = 0;
            s += 1;
            return s;
        } finally {
            lock.unlock();
        }
    }

java 锁性能对比_第1张图片

 

你可能感兴趣的:(JAVA,java)