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

第七十三篇 从电影院售票到停车场计数:生活场景解析Java原子类精髓

目录

    • 一、原子类基础:电影院售票系统
      • 1.1 传统售票的并发问题
      • 1.2 原子类解决方案
    • 二、原子类家族:超市收银系统
      • 2.1 基础类型原子类
      • 2.2 数组类型原子类
    • 三、CAS机制深度解析:停车场管理系统
      • 3.1 CAS工作原理
      • 3.2 车位计数器实现
    • 四、高性能实践:银行账户系统
      • 4.1 账户余额更新
      • 4.2 性能对比测试
    • 五、原子类进阶:电影院选座系统
      • 5.1 座位状态管理
      • 5.2 批量更新优化

想象电影院售票处:多个窗口同时售票却不会售出重复座位;停车场入口自动计数系统实时更新车位状态——这正是Java原子类的完美生活映射。本文将用日常场景揭秘高并发环境下的无锁编程奥秘。

一、原子类基础:电影院售票系统

1.1 传统售票的并发问题

// 非原子操作导致超卖
public class TicketCounter {private int totalTickets = 100;public void sellTicket() {if(totalTickets > 0) {// 此处可能被其他线程中断totalTickets--; System.out.println("售出1张票,剩余:" + totalTickets);}}
}

1.2 原子类解决方案

public class AtomicTicketCounter {private final AtomicInteger tickets = new AtomicInteger(100);public void safeSellTicket() {int current;do {current = tickets.get();if(current <= 0) {System.out.println("票已售罄");return;}} while(!tickets.compareAndSet(current, current - 1));System.out.println("安全售出,剩余:" + tickets.get());}
}

二、原子类家族:超市收银系统

2.1 基础类型原子类

// 收银台计数器
AtomicLong dailySales = new AtomicLong(0); // 每笔交易更新
void processTransaction(double amount) {// 累加销售额dailySales.addAndGet((long)(amount * 100));// 更新最高单笔交易AtomicReference<Double> maxTransaction = new AtomicReference<>(0.0);maxTransaction.accumulateAndGet(amount, Math::max);
}

2.2 数组类型原子类

// 货架商品库存
AtomicIntegerArray shelfStock = new AtomicIntegerArray(10); // 补充第3号货架商品
void restockShelf(int shelfId, int quantity) {shelfStock.addAndGet(shelfId, quantity);
}// 顾客购买商品
boolean purchaseItem(int shelfId) {int current;do {current = shelfStock.get(shelfId);if(current <= 0) return false;} while(!shelfStock.compareAndSet(shelfId, current, current-1));return true;
}

三、CAS机制深度解析:停车场管理系统

3.1 CAS工作原理

读取当前值
计算新值
当前值是否未变?
更新成功
重试操作

3.2 车位计数器实现

public class ParkingLot {private final AtomicInteger availableSpots;private final int totalSpots;public ParkingLot(int capacity) {this.totalSpots = capacity;this.availableSpots = new AtomicInteger(capacity);}// 车辆进入public boolean carEnter() {int current;do {current = availableSpots.get();if(current <= 0) return false;} while(!availableSpots.compareAndSet(current, current - 1));updateDisplay();return true;}// 车辆离开public void carExit() {availableSpots.incrementAndGet();updateDisplay();}private void updateDisplay() {System.out.println("当前车位: " + availableSpots + "/" + totalSpots);}
}

四、高性能实践:银行账户系统

4.1 账户余额更新

public class BankAccount {private final AtomicLong balance;public BankAccount(long initial) {this.balance = new AtomicLong(initial);}// 无锁存款public void deposit(long amount) {balance.addAndGet(amount);}// 安全取款(避免透支)public boolean withdraw(long amount) {long current;do {current = balance.get();if(current < amount) return false;} while(!balance.compareAndSet(current, current - amount));return true;}// 转账操作public boolean transferTo(BankAccount target, long amount) {if(this.withdraw(amount)) {target.deposit(amount);return true;}return false;}
}

4.2 性能对比测试

操作方式100万次操作耗时适用场景
synchronized450ms复杂事务处理
ReentrantLock380ms需要高级功能的场景
AtomicLong120ms简单计数器场景

五、原子类进阶:电影院选座系统

5.1 座位状态管理

public class SeatManager {// 使用AtomicReference数组管理座位状态private final AtomicReference<SeatStatus>[] seats;public SeatManager(int capacity) {seats = new AtomicReference[capacity];// 初始化所有座位为空闲Arrays.fill(seats, new AtomicReference<>(SeatStatus.AVAILABLE));}// 预订座位public boolean bookSeat(int seatId) {return seats[seatId].compareAndSet(SeatStatus.AVAILABLE, SeatStatus.OCCUPIED);}// 释放座位public void releaseSeat(int seatId) {seats[seatId].set(SeatStatus.AVAILABLE);}enum SeatStatus { AVAILABLE, OCCUPIED }
}

5.2 批量更新优化

// 使用LongAdder优化高频计数器
public class TicketCounter {private final LongAdder totalSales = new LongAdder();private final LongAdder vipSales = new LongAdder();public void sellTicket(boolean isVip) {totalSales.increment();if(isVip) vipSales.increment();}// 生成报表public void generateReport() {System.out.println("总售票: " + totalSales.sum());System.out.println("VIP票: " + vipSales.sum());}
}

🎯下期预告:《Java 并发容器》
💬互动话题:不深思则不能造于道。不深思而得者,其得易失
🏷️温馨提示:我是[随缘而动,随遇而安], 一个喜欢用生活案例讲技术的开发者。如果觉得有帮助,点赞关注不迷路🌟

http://www.xdnf.cn/news/11979.html

相关文章:

  • 如何搭建Z-Blog PHP版本:详细指南
  • pytorch 与 张量的处理
  • Neo4j 监控全解析:原理、技术、技巧与最佳实践
  • Neo4j 认证与授权:原理、技术与最佳实践深度解析
  • Elasticsearch中的语义搜索(Semantic Search)介绍
  • Axure 下拉框联动
  • Hive终极性能优化指南:从原理到实战
  • MySql安装、卸载(保姆级流程)
  • MCP客户端Client开发流程
  • python第42天打卡
  • html2canvas v1.0.0-alpha.12版本文本重叠问题修复
  • 基于LangChain构建高效RAG问答系统:向量检索与LLM集成实战
  • 泛微E8多行文本(textarea)赋值
  • 法律AI的“幻觉”治理:大模型如何重塑司法公正与效率
  • 基于 ShardingSphere + Seata 的最终一致性事务完整示例实现
  • nlohmann/json简介及使用
  • kubespere使用中遇到的问题
  • Elasticsearch的审计日志(Audit Logging)介绍
  • 若依Ruoyi中优先从本地文件加载静态资源
  • 42、响应处理-【源码分析】-浏览器与PostMan内容协商完全适配
  • Shopify 主题开发:促销活动页面专属设计思路
  • 【计算机】计算机存储器的分类与特性
  • 300道GaussDB(WMS)题目及答案。
  • Cursor 工具项目构建指南:Java 21 环境下的 Spring Boot Prompt Rules 约束
  • AI 时代下语音与视频伪造的网络安全危机
  • 服务器中僵尸网络攻击是指什么?
  • 联通专线赋能,亿林网络裸金属服务器:中小企业 IT 架构升级优选方案
  • MySQL JSON 查询中的对象与数组技巧
  • 【网络安全】fastjson原生链分析
  • Python 中 kwargs.get() 方法详解