//奶箱
package com.company;
public class Box {
private int mike;
private boolean state=false;//奶箱的状态 是否为满的
public synchronized void put(int mike) {
if (state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.mike = mike;
System.out.println("送奶员将第" + mike + "瓶奶放入奶箱中");
state = true;
notifyAll();
}
public synchronized void get() {
if (!state) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者获得第" + mike + "瓶奶");
state = false;
notifyAll();
}
}
//生产者
package com.company;
public class Producer implements Runnable{
private Box b;
@Override
public void run() {
for(int i=1;i<=5;i++)
{
b.put(i);
}
}
public Producer(Box b) {
this.b = b;
}
}
//消费者
package com.company;
public class Consunmer implements Runnable {
private Box b;
public Consunmer(Box b) {
this.b = b;
}
@Override
public void run() {
while (true) {
b.get();
}
}
}
//主函数
package com.company;
public class Main {
public static void main(String[] args) {
Box b = new Box();
Consunmer consunmer = new Consunmer(b);
Producer producer = new Producer(b);
Thread t1 = new Thread(consunmer);
Thread t2 = new Thread(producer);
t1.start();
t2.start();
}
}
那个在Box类中的put和get方法如果剩下的放在else里面就结果不对,不懂那个逻辑,state为假的时候执行wait()后面的代码就不会执行了嘛,这样的话加个else也是一样的呀
不加else: