public class Demo5 {
public static void main(String[] args) {
//准备数据
Product product = new Product();
//准备任务
Producer producer = new Producer(product);
Consumer consumer = new Consumer(product);
//准备生产线程消费线程
Thread pro = new Thread(producer);
Thread con = new Thread(consumer);
//开启线程
pro.start();
con.start();
}
}
//创建数据类--产品
class Product {
String name;//名字
double price;//价格
int number;//数量
//标识--控制唤醒等待
boolean flag = false;
//准备生产
public synchronized void setProduce(String name,double price){
if (flag == true){
try {wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.price = price;
System.out.println(Thread.currentThread().getName()+" 生产 了:"+this.name+" 价格:"+this.price+" 数量:"+this.number);
number++;
flag = !flag;
notify();
}
//准备消费
public synchronized void getConsume(){
if (flag == false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+" 消费 了:"+this.name+" 价格:"+this.price);
flag = !flag;
notify();
}
}
//创建生产任务
class Producer implements Runnable{
Product product;
public Producer(Product product) {
this.product = product;
}
@Override
public void run() {
while (true) {
product.setProduce("bingbing", 10);
}
}
}
//创建消费任务
class Consumer implements Runnable{
Product product;
public Consumer(Product product) {
this.product = product;
}
@Override
public void run() {
while (true) {
product.getConsume();
}
}
}