synchronized 对性能的影响

 
public static void main(String[] args) throws Exception {

    Runnable run1 = new Runnable() {
        public void run() {
            testCase(1);
        }
    };
    Runnable run2 = new Runnable() {
        public void run() {
            testCase(2);
        }
    };
    Runnable run3 = new Runnable() {
        public void run() {
            testCase(3);
        }
    };
    Runnable run4 = new Runnable() {
        public void run() {
            testCase(4);
        }
    };

    new Thread(run1).start();
//        new Thread(run2).start();
//        new Thread(run3).start();
//        new Thread(run4).start();
}

public static void testCase(int tid) {
    int n = 10000;
    for (int j = 0; j < 1; j++) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {

            nTestProcess();

        }
        System.out.println("normal test" + tid + " "
                + (System.currentTimeMillis() - start));

        start = System.currentTimeMillis();
        for (int i = 0; i < n; i++) {
            sTestProcess();
        }
        System.out.println("synchronized test" + tid + " "
                + (System.currentTimeMillis() - start));
    }
}

public static void testProcess() {
    int c = 1;
    for (int i = 1; i < 10000; i++) {
        c *= i;
        if (c % 2 == 0) {
            c += i;
        }
        if (i == 0) {
            throw new RuntimeException();
        }
    }
}

public static void nTestProcess() {
    testProcess();
}

public static synchronized void sTestProcess() {
    testProcess();
}

注意上面加红的代码

结果如下:

normal test1 318
synchronized test1 291

将加红代码注释去掉一个,结果如下:

normal test2 336
normal test1 348
synchronized test2 617
synchronized test1 631

加红代码注释去掉两个,结果如下:

normal test2 362
normal test3 392
normal test1 399
synchronized test3 892
synchronized test2 936
synchronized test1 935

加红代码注释全部去掉,结果如下:

normal test2 416
normal test4 420
normal test1 427
normal test3 436
synchronized test3 992
synchronized test2 1077
synchronized test4 1114
synchronized test1 1173

  

结论:直观结论时如果单线程运行时,锁机制对于性能并不影响;当多线程的时候锁机制对于性能影响显著;

比例:(617+631):(336+348) = 1.824

   (892+936+935):(362+392+399)= 2.396

     (992 + 1077 + 1114 + 1173) : (416 + 420 + 427 + 436) = 2.563

  增量分析  线程增多单个线程运行时间增多: 线程一起分享cpu 时间,每个线程获得cpu独享时间减少,因此单个线程运行时间增多

       线程增多,加锁方法与平常方法时间比增加:等待线程越多,单个线程等待时间越长。但是为何增加加速度在减少,目前不清楚。

原文地址:https://www.cnblogs.com/fantasy-es/p/4619077.html