JAVA 生产者消费者模型
生产者消费者问题(Producer-consumer problem),也称有限缓冲问题(Bounded-buffer problem),是一个多线程同步问题的经典案例。生产者生成一定量的数据放到缓冲区中,然后重复此过程;与此同时,消费者也在缓冲区消耗这些数据。生产者和消费者之间必须保持同步,要保证生产者不会在缓冲区满时放入数据,消费者也不会在缓冲区空时消耗数据。
实现该模型具有不止一种办法,本篇采用wait(),notifyAll()来实现,具体说明见代码注释。
生产者和消费者我设定了一定的sleep时间,以贴合实际并方便观察结果。
仓库#
public class Storage {
//仓库类
//仓库的最大容量
private final int maxSize=10;
//仓库当前货物数量
private int currentSize=0;
//生产方法
public synchronized void produce() { //注意一定要使用while循环阻塞不满足条件的情况
while(currentSize>=maxSize) { //wait()之后再次被唤醒将从wait后继续执行 所以使用if不行
System.out.println(Thread.currentThread().getName()+"仓库已满");
try {
wait();
} catch (InterruptedException e) {
}
}
currentSize++;
System.out.println(Thread.currentThread().getName()+"生产了一个产品 现库存为"+currentSize);
notifyAll();
}
//消费方法
public synchronized void consume() {
while(currentSize==0) {
System.out.println(Thread.currentThread().getName()+"仓库已空");
try {
wait();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
currentSize--;
System.out.println(Thread.currentThread().getName()+"消费类一个产品 现库存为"+currentSize);
notifyAll();
}
}
生产者#
public class Producer implements Runnable {
private Storage s;
public Producer(Storage s) {
this.s = s;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
s.produce();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}
}
消费者#
public class Consumer implements Runnable {
private Storage s;
public Consumer(Storage s) {
this.s = s;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(3000);
s.consume();
} catch (InterruptedException e) {
// TODO: handle exception
}
}
}
}
测试#
public class test {
public static void main(String[] args) {
Storage s=new Storage();
new Thread(new Producer(s),"生产者1").start();
new Thread(new Producer(s),"生产者2").start();
new Thread(new Producer(s),"生产者3").start();
new Thread(new Consumer(s),"消费者1").start();
new Thread(new Consumer(s),"消费者2").start();
new Thread(new Consumer(s),"消费者3").start();
}
}
作者:Kong Aobo
出处:https://www.cnblogs.com/kongaobo/p/14824844.html
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)