低价的网站建设wordpress 多功能插件下载
2026/4/8 11:08:43 网站建设 项目流程
低价的网站建设,wordpress 多功能插件下载,国内优秀门户网站设计,外国公司做网站文章目录安全库存类任意main方法里面调用使用说明并发情况下如何多节点执行并发问题一直是个小难点#xff0c;自动有了AtomicInteger类#xff0c;一切都变得简单了。安全库存类 这个类支持几种减库存的方法#xff0c;挺好的。 代码#xff1a; public class SafeInve…文章目录安全库存类任意main方法里面调用使用说明并发情况下如何多节点执行并发问题一直是个小难点自动有了AtomicInteger类一切都变得简单了。安全库存类这个类支持几种减库存的方法挺好的。代码publicclassSafeInventory{privatefinalAtomicIntegerstock;privatefinalAtomicIntegertotalSalesnewAtomicInteger(0);publicSafeInventory(intinitialStock){this.stocknewAtomicInteger(initialStock);}/** * 扣减库存 - 方法1使用 compareAndSet (CAS) * 适合复杂的扣减逻辑 */publicbooleandeductWithCAS(intquantity){while(true){intcurrentstock.get();if(currentquantity){returnfalse;// 库存不足}intnewValuecurrent-quantity;if(stock.compareAndSet(current,newValue)){totalSales.addAndGet(quantity);returntrue;}// CAS失败循环重试}}/** * 扣减库存 - 方法2使用 decrementAndGet * 适合每次扣减1个的情况 */publicbooleandeductOne(){while(true){intcurrentstock.get();if(current0){returnfalse;// 库存不足}if(stock.compareAndSet(current,current-1)){totalSales.incrementAndGet();returntrue;}// CAS失败重试}}/** * 扣减库存 - 方法3更优雅的实现 */publicbooleandeduct(intquantity){intcurrent,newValue;do{currentstock.get();if(currentquantity){returnfalse;}newValuecurrent-quantity;}while(!stock.compareAndSet(current,newValue));totalSales.addAndGet(quantity);returntrue;}publicintgetStock(){returnstock.get();}publicintgetTotalSales(){returntotalSales.get();}}任意main方法里面调用代码publicstaticvoidmain(String[]args)throwsException{intthreadCount200;intinitialStock100;SafeInventoryinventorynewSafeInventory(initialStock);CountDownLatchlatchnewCountDownLatch(threadCount);ExecutorServiceexecutorExecutors.newFixedThreadPool(threadCount);System.out.println(使用 AtomicInteger 解决方案);System.out.println(初始库存: initialStock);System.out.println(并发线程数: threadCount);// 记录成功购买的线程数AtomicIntegersuccessCountnewAtomicInteger(0);for(inti0;ithreadCount;i){finalintuserIdi;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分配节点。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询