//这是一个测试类
public class Demo {
public static void main(String[] args) {
Produce pc = new Produce();//创建货物对象
PudThred produce = new PudThred(pc);//生产者实现了runnable接口复写run方法
ChThred chThred = new ChThred(pc);//因为需要PC对象来实现一个同步锁
Thread sc= new Thread(produce,"生产者:");//创建生产者线程
Thread xf= new Thread(chThred,"消费者:");//创建消费者线程
sc.start();// 开启线程之后调用本地的run方法,而run方法却是produce的run方法,
xf.start();
}
}
//这是一个生产的者
public class PudThred implements Runnable {//实现了Runnale接口必须复写RUN方法等待线程启动
Produce a;//目的为一个对象的操作
public PudThred(Produce pc){
this.a = pc; //PC传入的对象与A是一个对象指向一个内存地址
}
@Override
public void run() {
while(true){
synchronized (a) { //用同一个对象来创建同步锁
if(a.flag){ //进屋,锁门,判断是否现在缺货,如果是false,跳过此步骤,
try {
a.wait();//如果是true,证明现在货物已经满了,进货该停止了,休眠。
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(a.getName()==null&&a.getName1()==null){//如果 产品名字是空,就进货橘子
a.setName("苹果");
a.setName1("橘子");
}
if(a.num<=10){//如果货物为零库存,就使劲的造到第10个,
System.out.println(a.getName()+"和"+a.getName1() + "被生产了:" + (++a.num) +"个");
}
if(a.num==10){//当且仅当橘子货物到达10个时候,库存已经满了,就把flag=true,休眠
a.flag=true;
a.notify();// 唤醒正在休眠的线程
}
}
}
}
}
//这是一个消费者
public class ChThred implements Runnable {
Produce a;
public ChThred(Produce pc) {
this.a = pc;
}
@Override
public void run() {
while (true) {
synchronized (a) {
if (!a.flag) {
try {
a.wait();// 如果货物为0,是FALSE,就休眠,不要卖货
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (a.num >= 0) {
System.out.println(a.getName()+a.getName1() + "第:" + a.num-- +"个,被消费了");
}
if(a.num==0){
a.flag=false;
a.notify();
}
}
}
}
}
//被封装的简单货物类
public class Produce {
private String name;//产品名字
private String name1;
int num;//产品数量
boolean flag = false;//库存标记
public Produce() {//创建对象的构造函数
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
}
public class ChThred implements Runnable {
Produce a;
public ChThred(Produce pc) {
this.a = pc;
}
@Override
public void run() {
while (true) {
synchronized (a) {
if (!a.flag) {
try {
a.wait();// 如果货物为0,是FALSE,就休眠,不要卖货
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (a.num >= 0) {
System.out.println(a.getName()+a.getName1() + "第:" + a.num-- +"个,被消费了");
}
if(a.num==0){
a.flag=false;
a.notify();
}
}
}
}
}
本文深入探讨了使用多线程同步机制实现生产者消费者模型的原理及其实现过程,通过实例展示了如何利用Java语言实现同步锁、等待、通知等关键概念,确保在高并发环境下数据的一致性和正确性。
 和 消费者(卖货),让其进行有序的先生产和后消费&spm=1001.2101.3001.5002&articleId=42010493&d=1&t=3&u=7c20dd0164594956901f9d2e5c2b89fe)
2783

被折叠的 条评论
为什么被折叠?



