news 2026/5/16 8:44:11

AtomicInteger实现安全减库存

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
AtomicInteger实现安全减库存

文章目录

        • 安全库存类
        • 任意main方法里面调用
        • 使用说明
        • 并发情况下如何多节点执行

并发问题一直是个小难点,自动有了AtomicInteger类,一切都变得简单了。
安全库存类

这个类支持几种减库存的方法,挺好的。

代码:

publicclassSafeInventory{privatefinalAtomicIntegerstock;privatefinalAtomicIntegertotalSales=newAtomicInteger(0);publicSafeInventory(intinitialStock){this.stock=newAtomicInteger(initialStock);}/** * 扣减库存 - 方法1:使用 compareAndSet (CAS) * 适合复杂的扣减逻辑 */publicbooleandeductWithCAS(intquantity){while(true){intcurrent=stock.get();if(current<quantity){returnfalse;// 库存不足}intnewValue=current-quantity;if(stock.compareAndSet(current,newValue)){totalSales.addAndGet(quantity);returntrue;}// CAS失败,循环重试}}/** * 扣减库存 - 方法2:使用 decrementAndGet * 适合每次扣减1个的情况 */publicbooleandeductOne(){while(true){intcurrent=stock.get();if(current<=0){returnfalse;// 库存不足}if(stock.compareAndSet(current,current-1)){totalSales.incrementAndGet();returntrue;}// CAS失败,重试}}/** * 扣减库存 - 方法3:更优雅的实现 */publicbooleandeduct(intquantity){intcurrent,newValue;do{current=stock.get();if(current<quantity){returnfalse;}newValue=current-quantity;}while(!stock.compareAndSet(current,newValue));totalSales.addAndGet(quantity);returntrue;}publicintgetStock(){returnstock.get();}publicintgetTotalSales(){returntotalSales.get();}}
任意main方法里面调用

代码:

publicstaticvoidmain(String[]args)throwsException{intthreadCount=200;intinitialStock=100;SafeInventoryinventory=newSafeInventory(initialStock);CountDownLatchlatch=newCountDownLatch(threadCount);ExecutorServiceexecutor=Executors.newFixedThreadPool(threadCount);System.out.println("使用 AtomicInteger 解决方案");System.out.println("初始库存: "+initialStock);System.out.println("并发线程数: "+threadCount);// 记录成功购买的线程数AtomicIntegersuccessCount=newAtomicInteger(0);for(inti=0;i<threadCount;i++){finalintuserId=i;executor.submit(()->{try{// 模拟网络延迟Thread.sleep(ThreadLocalRandom.current().nextInt(10,30));// 尝试购买if(inventory.deductOne()){successCount.incrementAndGet();System.out.println("用户"+userId+" 购买成功,剩余库存: "+inventory.getStock());}else{System.out.println("用户"+userId+" 库存不足");}}catch(InterruptedExceptione){Thread.currentThread().interrupt();}finally{latch.countDown();}});}latch.await();executor.shutdown();System.out.println("\n========== 最终统计 ==========");System.out.println("成功购买人数: "+successCount.get());System.out.println("最终库存: "+inventory.getStock());System.out.println("总销售量: "+inventory.getTotalSales());// 验证正确性if(inventory.getStock()==initialStock-successCount.get()&&inventory.getStock()>=0){System.out.println("✓ 库存扣减正确!");}else{System.out.println("✗ 库存扣减错误!");}}
使用说明

不同的商品可以分别创建SafeInventory对象,表示每个商品有各自的库存值
根据实际需要在线程主体里调用对应的减库存方法(减一个,或减多个等)

并发情况下如何多节点执行

可以用redis锁实现一个节点执行,每波并发只在一个节点执行,待并发完成,库存写库后下次再根据redis分配节点。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/10 22:28:43

基于Spring Boot题库及试卷管理系统

基于Spring Boot题库及试卷管理系统 是一种基于Spring Boot框架开发的在线教育和考试管理工具。以下是对该系统的详细介绍&#xff1a; 一、系统背景与意义 随着教育数字化的推进和在线学习需求的增长&#xff0c;传统的纸质考试方式已经逐渐显示出局限性&#xff0c;特别是在灵…

作者头像 李华
网站建设 2026/5/10 22:29:53

基于Spring Boot汽车租赁系统

基于Spring Boot汽车租赁系统 是一个基于Spring Boot框架开发的汽车租赁管理平台&#xff0c;它整合了当前前沿的技术框架和组件&#xff0c;为用户提供一站式的租车解决方案&#xff0c;并提升租车公司的运营效率和管理水平。以下是对该系统的详细介绍&#xff1a; 一、系统架…

作者头像 李华
网站建设 2026/5/8 21:11:49

淘宝天猫需要3c认证怎么办?

淘宝天猫上销售属于 3C 强制认证目录内的产品&#xff08;如家电、数码充电器等&#xff09;&#xff0c;必须按正规流程办 3C 认证并完成平台备案&#xff0c;否则商品可能下架、店铺面临扣分。具体处理方式分自有货源和采购货源两种情况&#xff0c;详细流程如下&#xff1a;…

作者头像 李华
网站建设 2026/5/8 21:11:54

出口美国的电子电器产品需要做FCC认证吗?

出口美国的电子电器产品是否需要做 FCC 认证&#xff0c;要根据产品是否产生电磁辐射、是否具备主动射频发射功能来判断&#xff0c;分为两种情况&#xff1a;必须做 FCC 认证的产品具备主动射频发射功能的产品&#xff1a;比如带蓝牙、Wi-Fi、蜂窝通信的电子设备&#xff0c;这…

作者头像 李华
网站建设 2026/5/8 12:34:33

《国产数据库技术》学习心得:DM数据库实践之路

在数字化转型加速推进的背景下&#xff0c;国产数据库的重要性日益凸显。本学期通过《国产数据库技术》课程的学习&#xff0c;我重点钻研了达梦数据库&#xff08;DM&#xff09;的核心技术&#xff0c;从环境搭建到实操应用&#xff0c;逐步掌握了其安装配置、备份还原、SQL编…

作者头像 李华