50,639
社区成员
![](https://csdnimg.cn/release/cmsfe/public/img/topic.427195d5.png)
![](https://csdnimg.cn/release/cmsfe/public/img/me.40a70ab0.png)
![](https://csdnimg.cn/release/cmsfe/public/img/task.87b52881.png)
![](https://csdnimg.cn/release/cmsfe/public/img/share-circle.3e0b7822.png)
//经典的生产者与消费者问题,线程的通讯知识点
class product1{//定义一个产品类
String name="apple";
double price;
int number;
boolean flag=false;
}
class producer1 extends Thread{//定义一个生产者类
product1 p;//定义一个产品对象的饮用
public producer1(product1 p) {
// TODO Auto-generated constructor stub
this.p=p;
}
@Override
public void run() {
int number=0;
while(true){
synchronized(p){
if(p.flag=false){
if(number%2==0){
p.name="apple";
p.price=2.5;
}
else{
p.name="blanana";
p.price=1.5;
}
System.out.println("生产的产品:"+p.name+"价格:"+p.price);
System.out.println("生产后的商品数量:"+number);
p.flag=true;
number++;
p.notifyAll();
} else
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class custumer extends Thread{
product1 p;//定义一个产品对象的饮用
public custumer(product1 p) {
// TODO Auto-generated constructor stub
this.p=p;
}
@Override
public void run(){
while(true){
synchronized (p) {
if(p.flag=true)
{
System.out.println("消费: "+p.name+"价格是:"+p.price);
p.flag=false;
p.notifyAll();
} else{
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
}
}
}
public class demo1{
public static void main(String[]args) throws InterruptedException{
product1 p=new product1();
producer1 thread1=new producer1(p);
custumer thread2=new custumer(p);
thread1.start();
thread2.start();
}
}