標籤:
測試主要從已耗用時間差來體現,資料量越大,時間差越明顯,例子如下:
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並發,同步鎖效能測試