JAVA并发,同步锁性能测试

测试主要从运行时间差来体现,数据量越大,时间差越明显,例子如下:

 1 package com.xt.thinks21_2;
 2 
 3 /**
 4  * 同步锁性能测试
 5  * 
 6  * @author Administrator
 7  *
 8  */
 9 public class SynchronizedTimeTest {
10     public volatile int inc = 0;
11 
12     public void increase() {
13         inc++;
14     }
15 
16     public static void main(String[] args) {
17         final SynchronizedTimeTest test = new SynchronizedTimeTest();
18         for (int i = 0; i < 10; i++) {
19             new Thread() {
20                 public void run() {
21                     for (int j = 0; j < 10000; j++)
22                         test.increase();
23                 };
24             }.start();
25         }
26         Long time1 = System.currentTimeMillis();
27         while (Thread.activeCount() > 1) {
28             // 保证前面的线程都执行完
29             Thread.yield();
30         }
31         Long time2 = System.currentTimeMillis();
32         System.out.println("time1:" + time1 + " time2:" + time2);
33         Long timeDiff = time2 - time1;
34         System.out.println("time:" + timeDiff + "-->" + test.inc);
35     }
36 }

上面是方法未加synchronized运行结果:

time1:1429805281187 time2:1429805281187
time:0–>75809

方法添加synchronized运行结果:

time1:1429805416628 time2:1429805416645
time:17–>100000

    原文作者:java锁
    原文地址: http://www.cnblogs.com/wubingshenyin/p/4452236.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞