蜜蜂和熊的問題
- 100只蜜蜂,2頭熊,每隻蜜蜂每次生產的蜂蜜是1,有一個罐子,容量是50
- 罐子的蜂蜜量一旦到達20,熊就一次喫掉20
注意問題
- 生產和消費函數在等待結束執行完生產消費邏輯後要
notifyAll()
- 生產者和消費者執行完生產消費函數後要
yield()
- 以上兩點可以保證蜂蜜到達20以後熊儘快開始消費,不然總是等到罐子滿了熊纔開始消費。
代碼
App.java
public static void main(String[] args) throws Exception {
HoneyPot pot = new HoneyPot();
Bear bear1 = new Bear("bear1", pot);
Bear bear2 = new Bear("bear2", pot);
bear1.start();
bear2.start();
for(int i=1;i<=100;i++){
new Bee(Integer.toString(i), pot).start();
}
}
HoneyPot.java
public class HoneyPot {
int honey;
private final static int capacity = 50;
synchronized void add(int i) throws InterruptedException {
while (honey == capacity) {
this.wait();
}
honey += i;
System.out.println("added, pot cp: " + honey);
this.notifyAll();
}
synchronized void remove(int i) throws InterruptedException {
while (honey < i) {
this.wait();
}
honey -= i;
System.out.println("removed, pot cp: " + honey);
this.notifyAll();
}
}
Bee.java
public class Bee extends Thread {
private String bname;
private HoneyPot hp;
Bee(String bname, HoneyPot hp){
this.bname = bname;
this.hp = hp;
}
@Override
public void run() {
while(true){
try {
hp.add(1);
System.out.println(bname + " : +1");
this.yield();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Bear.java
public class Bear extends Thread {
private String bname;
private final static int drink = 20;
private HoneyPot hp;
Bear(String bname, HoneyPot hp) {
this.bname = bname;
this.hp = hp;
}
@Override
public void run() {
while (true) {
try {
hp.remove(drink);
System.out.println(bname + " - : " + drink);
this.yield();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}