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

Java生产者消费者模式实战解析

Java生产者消费者模式实战解析

      • 异步模式
        • 传统版
        • 改进版
        • 阻塞队列

异步模式

传统版

异步模式之生产者/消费者:

classShareData{privateintnumber=0;privateLocklock=newReentrantLock();privateConditioncondition=lock.newCondition();publicvoidincrement()throwsException{// 同步代码块,加锁lock.lock();try{// 判断 防止虚假唤醒while(number!=0){// 等待不能生产condition.await();}// 干活number++;System.out.println(Thread.currentThread().getName()+"\t "+number);// 通知 唤醒condition.signalAll();}catch(Exceptione){e.printStackTrace();}finally{lock.unlock();}}publicvoiddecrement()throwsException{// 同步代码块,加锁lock.lock();try{// 判断 防止虚假唤醒while(number==0){// 等待不能消费condition.await();}// 干活number--;System.out.println(Thread.currentThread().getName()+"\t "+number);// 通知 唤醒condition.signalAll();}catch(Exceptione){e.printStackTrace();}finally{lock.unlock();}}}publicclassTraditionalProducerConsumer{publicstaticvoidmain(String[]args){ShareDatashareData=newShareData();// t1线程,生产newThread(()->{for(inti=0;i<5;i++){shareData.increment();}},"t1").start();// t2线程,消费newThread(()->{for(inti=0;i<5;i++){shareData.decrement();}},"t2").start();}}
改进版

异步模式之生产者/消费者:

  • 消费队列可以用来平衡生产和消费的线程资源,不需要产生结果和消费结果的线程一一对应
  • 生产者仅负责产生结果数据,不关心数据该如何处理,而消费者专心处理结果数据
  • 消息队列是有容量限制的,满时不会再加入数据,空时不会再消耗数据
  • JDK 中各种阻塞队列,采用的就是这种模式

publicclassdemo{publicstaticvoidmain(String[]args){MessageQueuequeue=newMessageQueue(2);for(inti=0;i<3;i++){intid=i;newThread(()->{queue.put(newMessage(id,"值"+id));},"生产者"+i).start();}newThread(()->{while(true){try{Thread.sleep(1000);Messagemessage=queue.take();}catch(InterruptedExceptione){e.printStackTrace();}}},"消费者").start();}}//消息队列类,Java间线程之间通信classMessageQueue{privateLinkedList<Message>list=newLinkedList<>();//消息的队列集合privateintcapacity;//队列容量publicMessageQueue(intcapacity){this.capacity=capacity;}//获取消息publicMessagetake(){//检查队列是否为空synchronized(list){while(list.isEmpty()){try{sout(Thread.currentThread().getName()+":队列为空,消费者线程等待");list.wait();}catch(InterruptedExceptione){e.printStackTrace();}}//从队列的头部获取消息返回Messagemessage=list.removeFirst();sout(Thread.currentThread().getName()+":已消费消息--"+message);list.notifyAll();returnmessage;}}//存入消息publicvoidput(Messagemessage){synchronized(list){//检查队列是否满while(list.size()==capacity){try{sout(Thread.currentThread().getName()+":队列为已满,生产者线程等待");list.wait();}catch(InterruptedExceptione){e.printStackTrace();}}//将消息加入队列尾部list.addLast(message);sout(Thread.currentThread().getName()+":已生产消息--"+message);list.notifyAll();}}}finalclassMessage{privateintid;privateObjectvalue;//get set}

阻塞队列
publicstaticvoidmain(String[]args){ExecutorServiceconsumer=Executors.newFixedThreadPool(1);ExecutorServiceproducer=Executors.newFixedThreadPool(1);BlockingQueue<Integer>queue=newSynchronousQueue<>();producer.submit(()->{try{System.out.println("生产...");Thread.sleep(1000);queue.put(10);}catch(InterruptedExceptione){e.printStackTrace();}});consumer.submit(()->{try{System.out.println("等待消费...");Integerresult=queue.take();System.out.println("结果为:"+result);}catch(InterruptedExceptione){e.printStackTrace();}});}

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

相关文章:

  • 别再数据线了!用FastAPI 分钟搭个局域网文件+剪贴板神器谓
  • 冷库维护上门服务全攻略:这些疑问你肯定也有
  • Speechless:终极微博备份指南 - 如何3分钟将微博内容安全导出为PDF
  • AlmaLinux构建LNMP
  • SITS2026架构白皮书解密:为什么92%的传统Serverless团队将在2026年前被迫重构?
  • DLT645-2007协议常见报文错误排查指南:从校验失败到数据域乱码
  • 算法·贪心
  • AI原生DevOps流水线重构(奇点大会闭门报告节选):CI/CD→AI/CD的8项指标迁移清单
  • 揭秘2026奇点智能技术大会核心成果:如何用AI原生审查引擎将PR平均审核时长从47分钟压缩至93秒?
  • Windows任务栏个性化定制完全指南:7+ Taskbar Tweaker使用教程
  • RESTful API设计完整手册:http-api-guide最佳实践
  • LCD显示屏接口
  • 老马失前蹄,竟然在数据库外键上翻车了,重温外键级联巡
  • STC8H单片机学习-GPIO的四种模式
  • 轴承故障诊断避坑指南:东南大学数据集实战中,80%的人会忽略的GAF参数设置与模型调优细节
  • YOLOv11新版本解读:结合Phi-4-mini-reasoning分析技术演进与适用场景
  • 如何快速配置炉石传说智能脚本:新手的完整入门攻略
  • Bilibili-Evolved:终极B站增强脚本的完整指南
  • 如何免费实现PotPlayer字幕在线翻译:百度翻译插件完整指南
  • 前端可访问性:别让你的应用变成残疾人的噩梦
  • YOLOv5+DeepSORT实战:从零搭建目标检测与跟踪系统(含代码优化)
  • 【书生·浦语】internlm2-chat-1.8b在医疗健康领域应用:症状自查与报告解读
  • Cursor Pro破解全攻略:简单三步实现AI编程神器永久免费使用终极指南
  • CosyVoice语音生成大模型-300M-25Hz学术应用:配合MathType公式的理工科教学音频生成
  • RTX4090D专属Qwen-Image镜像:电商商品识别与图文问答实战
  • 5分钟极速上手:华硕笔记本终极性能控制工具G-Helper完全指南
  • 终极指南:如何用VideoSrt为视频快速生成专业字幕
  • 直驱永磁风机并网Chopper低电压穿越的Matlab Simulink仿真
  • Untrunc视频修复工具:专业恢复损坏MP4/MOV文件的终极指南
  • 【2026奇点大会权威选型白皮书】:AI原生数据库TOP5实战对比(TPC-AI基准实测+LLM推理延迟压测数据)