• 多线程并发安全计数器实现限流(二) 使用 J.U.C中的AtomicInteger实现计数器


     一、使用 J.U.C中的 atomicInteger 实现计数器

            由于(一)中的计数器不能保证并发安全,因此需要改一下;

           思路:使用 J.U.C中的 AtomicInteger 实现计数器

    二、实现

    public class CounterAtomic implements Counter {
    
        // JUC包 针对基本数据类型 --- 原子操作
        AtomicInteger i = new AtomicInteger(0); // 本质是修改内存中某一个变量的值
    
        public int incr() {
            return i.incrementAndGet();
        }
    
        public int decr() {
            return i.decrementAndGet();
        }
    
        @Override
        public int get() {
            return i.get();
        }
    }
    

       

    测试代码

        public static void main(String[] args) throws InterruptedException {
            final Counter ct = new CounterAtomic();
    
            //模拟多线程场景
            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...运算时间: 1067600
    done...运算时间: 2265100
    计数器最终结果: 20000
  • 相关阅读:
    Web Storage
    You don't know js
    vue—你必须知道的
    js数据类型
    Python基础 — Matplotlib
    Python基础 — Pandas
    MySQL基础 — 常用命令
    MySQL基础 — 详细安装
    Python机器学习算法 — 支持向量机(SVM)
    Python机器学习算法 — 逻辑回归(Logistic Regression)
  • 原文地址:https://www.cnblogs.com/Jomini/p/13621952.html
Copyright © 2020-2023  润新知