java生产者消费者模型
/**
- 生成者,消费者,产品,容器
- @author Administrator
*/
public class ProducerConsumer {
public static void main(String[] args) {
Container ct = new Container();//生成容器
//生产者消费者拥有同一个容器
Producer p = new Producer(ct);
Consumer c = new Consumer(ct);
Thread t1 = new Thread(p);//生产者线程
Thread t2 = new Thread(c);//消费者线程
//Thread t3 = new Thread(c);//消费者线程
//Thread t4 = new Thread(c);//消费者线程
t1.start();
t2.start();
}
}
//1.先定义产品类
class Product{
//产品id
int id ;
Product(int id){
this.id = id;
}
public String toString(){
return "product"+id;
}
}
//2.再定义容器类
class Container{
//定义容器的容量
Product [] p = new Product[5];
//容器当前存放产品位置
int index =0;
//往容器里放东西
public synchronized void put(Product pro){
while(indexp.length){
try {
//生产满了要等待消费
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//唤醒生产者
this.notify();
p[index] = pro;
System.out.println("生产了"+pro);
index++;
}
//从容器中拿走产品
public synchronized Product get(){
//因为index位置没有产品,所以要先--
while(index0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
Product p2 = p[index];
System.out.println("消费了"+p2);
return p2;
}
}
//定义生产者实现了Runnable接口
class Producer implements Runnable{
Container c = null;
Producer(Container c){
this.c = c;
}
@Override
public void run() {
//生产了30个产品
for(int x = 1;x<=30;x++){
Product p = new Product(x);
//往里面放产品
c.put(p);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//4.定义消费者从里面拿东西也实现Runnable接口
class Consumer implements Runnable{
Container c = null;
Consumer(Container c){
this.c = c;
}
@Override
public void run() {
for(int x = 1;x<=30;x++){
//从里面拿产品
c.get();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人