public class Test01 {
public static void main(String[] args) {
Phone phone = new Phone();
Producer p1 = new Producer(phone);
Producer p2 = new Producer(phone);
Consumer c1 = new Consumer(phone);
Consumer c2 = new Consumer(phone);
p1.start();
p2.start();
c1.start();
c2.start();
}
public class Phone {
private String brand;
public double price;
private boolean store;//库存
public boolean isStore() {
return store;
}
public void setStore(boolean store) {
this.store = store;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Phone() {
}
public Phone(String brand, double price) {
this.brand = brand;
this.price = price;
}
}
//生产者线程
public class Producer extends Thread{
private Phone phone;
public Producer(Phone phone) {
this.phone = phone;
}
private static boolean flag = true;
@Override
public void run() {
while (true){
synchronized (phone){
while (phone.isStore()) {//有库存
try {
phone.wait();//等待:1.让当前线程进入阻塞状态 2.释放锁资源3.将当前线程记录到对象监视器中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (flag){
phone.setBrand("华为");
phone.setPrice(3999);}
else {
phone.setBrand("小米");
phone.setPrice(1999);
}
flag = !flag;
phone.setStore(true);
phone.notifyAll();//唤醒对象中所有等待线程
}
}
}
//消费者线程
public class Consumer extends Thread{
private Phone phone;
public Consumer(Phone phone) {
this.phone=phone;
}
@Override
public void run() {
while (true) {
synchronized (phone) {
while (!phone.isStore()) {//没有库存
try {
phone.wait();//等待:1.让当前线程进入阻塞状态 2.释放锁资源3.将当前线程记录到对象监视器中
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System .out.println(phone.getBrand()+"----"+phone.getPrice());
phone.setStore(false);
phone.notifyAll();//唤醒对象中所有等待线程
}
}
}