测试主要从运行时间差来体现,数据量越大,时间差越明显,例子如下:
package com.xt.thinks21_2; /**
* 同步锁性能测试
*
* @author Administrator
*
*/
public class SynchronizedTimeTest {
public volatile int inc = ; public void increase() {
inc++;
} public static void main(String[] args) {
final SynchronizedTimeTest test = new SynchronizedTimeTest();
for (int i = ; i < ; i++) {
new Thread() {
public void run() {
for (int j = ; j < ; j++)
test.increase();
};
}.start();
}
Long time1 = System.currentTimeMillis();
while (Thread.activeCount() > ) {
// 保证前面的线程都执行完
Thread.yield();
}
Long time2 = System.currentTimeMillis();
System.out.println("time1:" + time1 + " time2:" + time2);
Long timeDiff = time2 - time1;
System.out.println("time:" + timeDiff + "-->" + test.inc);
}
}
上面是方法未加synchronized运行结果:
time1:1429805281187 time2:1429805281187
time:0-->75809
方法添加synchronized运行结果:
time1:1429805416628 time2:1429805416645
time:17-->100000