Java 多线程实现蜜蜂和熊的问题

蜜蜂和熊的问题

  • 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();
            }
        }
    }
}
发布了66 篇原创文章 · 获赞 21 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_35753140/article/details/100156050