当前位置: 首页 > news >正文

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分配节点。

http://www.cnnetsun.cn/news/116024.html

相关文章:

  • 基于springboot面料花型试衣系统
  • 域名被污染是什么意思?还能不能继续使用?
  • Python大数据基于深度学习的音乐推荐系统-250326--论文
  • Python大数据影评情感分析可视化及推荐系统的设计与实现_u5ck1y17_论文
  • AI Agent设计模式大揭秘:9种架构让你从编程小白变身架构师!
  • Python大数据基于Spark的南昌房价数据分析系统的设计与实现_45i0b357_论文
  • 9 个降AI率工具,自考人必备的降重神器!
  • 9 个降AI率工具,自考人必备!
  • 旅行记录应用新建旅行 - Cordova OpenHarmony 混合开发实战
  • 9 个降AI率工具推荐,继续教育学生必备
  • Java八股文(Java基础面试题)
  • 邦芒忠告:职场中没有好人缘的10种人
  • 基于Spring Boot人才招聘管理系统
  • 拒绝“魔法值”注入:手把手教你实现 Spring Boot 高性能枚举校验注解 @InEnum
  • 国内容易上手的claudecode一键配置指南
  • 复原IP地址
  • Redis 发布订阅
  • JQuery支持WebUploader完成百万文件断点续传的原理?
  • Vue3如何结合组件实现大文件分片的并行上传优化?
  • 类型分布统计-Cordovaopenharmony多维分析实战
  • 四时四名,一山万象:朝鲜金刚山的锦绣风姿
  • 基于Spring Boot的果蔬销售系统
  • Scala Collection(集合)
  • 介观交通流仿真软件:DynusT_(11).交通事件管理
  • django基于Python天气分析系统
  • python基于大数据的分析长沙旅游景点推荐系统
  • 基于Django的学分管理系统
  • 广度优先遍历与最短路径
  • 通信系统仿真:通信系统基础理论_(11).光通信技术
  • 17、Linux文件与目录操作全解析