JAVA並發,同步鎖效能測試

來源:互聯網
上載者:User

標籤:

測試主要從已耗用時間差來體現,資料量越大,時間差越明顯,例子如下:

 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並發,同步鎖效能測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.