多執行緒併發安全計數器實現限流(三) 加鎖實現計數器
阿新 • • 發佈:2020-09-06
一、加鎖實現計數器
public class CounterSync implements Counter { volatile int i = 0; // 本質是修改記憶體中某一個變數的值 public synchronized int incr() { return i++; } public int decr() { return i--; } @Override public int get() { return i; } }
二、測試
public static void main(String[] args) throws InterruptedException { final Counter ct = new CounterSync(); //模擬多執行緒場景 CountDownLatch countDownLatch = new CountDownLatch(2); for (int i = 0; i < 2; i++) { new Thread(() -> { long begin = System.nanoTime(); for (int j = 0; j < 10000; j++) { ct.incr(); } System.out.println("done...運算時間: " + (System.nanoTime() - begin)); countDownLatch.countDown(); }).start(); } countDownLatch.await(); System.out.println("計數器最終結果: " + ct.get()); // 預期結果應該 --- 20000 }
三、列印結果
done...運算時間: 1173900
done...運算時間: 803900
計數器最終結果: 20000