多线程并发安全计数器实现限流(三) 加锁实现计数器
一、加锁实现计数器
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