package com.heilong.thread;
//产品类
class Product{
String name;
double price;
boolean flag = false; //产品是否生成完毕的标志。默认没有生产完毕
}
//生产者
class Producer extends Thread{
Product p;
public Producer(Product p){
this.p = p;
}
@Override
public void run() {
int i = 0;
while(true){
synchronized (p) {
if(p.flag==false){
if(i%2==0){
p.name = "苹果";
p.price = 6.5;
}else{
p.name = "香蕉";
p.price = 2.0;
}
System.out.println("生产者生产了" + p.name + " 价格:" + p.price);
p.flag = true;
i++;
p.notify();
}else{
//已经生产完毕,等待消费者消费
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//消费者
class Customer extends Thread{
Product p;
public Customer(Product p){
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.notify();
}else{
try {
p.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class producer_customer {
public static void main(String[] args) {
Product p = new Product();
//创建生产者对象
Producer producer = new Producer(p);
//创建消费者对象
Customer customer = new Customer(p);
producer.start();
customer.start();
}
}
Java线程案例之生产者与消费者
最新推荐文章于 2024-04-15 17:02:22 发布