生产者-消费者问题就是线程协作的问题,notify通知的时候,会先唤醒等待时间最长的对象,因此不用担心自己唤醒自己的情况。
public static void main(String[] args) {
Baozi baozi = new Baozi();
baozi.flag = false;
Chihuo Chihuo = new Chihuo("吃货", baozi);
Chihuo.start();
Baozipu Baozipu = new Baozipu("包子铺", baozi);
Baozipu.start();
}
public static class Chihuo extends Thread {
private Baozi baozi;
public Chihuo(String name, Baozi baozi) {
super(name);
this.baozi = baozi;
}
@Override
public void run() {
super.run();
while (true) {
synchronized (baozi) {
if (!baozi.flag) {
try {
System.out.println("没有包子,吃货在等待");
baozi.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("有包子,吃货吃了包子");
baozi.flag = false;
System.out.println("吃货吃完了包子,通知包子铺做包子");
baozi.notify();//不用担心会唤醒自己,它会唤醒等待时间最长的对象
}
}
}
}
public static class Baozipu extends Thread {
private Baozi baozi;
public Baozipu(String name, Baozi baozi) {
super(name);
this.baozi = baozi;
}
@Override
public void run() {
super.run();
int count = 0;
while (true) {
synchronized (baozi) {
if (baozi.flag) {
try {
System.out.println("有包子,包子铺在等待");
baozi.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("没有包子,包子铺要做包子");
count++;
baozi.count = count;
System.out.println("包子铺做好包子,通知吃货吃包子");
baozi.notify();
baozi.flag = true;
}
}
}
}