java学习-----例子2

题目:用多线程模拟蜜蜂和熊的关系。
100只蜜蜂是生产者,2只熊是消费者,蜜蜂生产蜂蜜是累加的过程,熊吃蜂蜜是批量(满20吃掉)的过程。生产者与消费者之间是用通信方式告诉对方,注意不能出现死锁的现象。
参考代码:

public class BeeDemo {
    public static void main(String[] args){
            Box box = new Box();
            for(int i=1;i<=100;i++){
                new Bee("Bee-"+i,box).start();
            }
            new Bear("熊大",box).start();
            new Bear("熊二",box).start();
    }

}
//蜜蜂
class Bee extends Thread{
    private String name;
    private Box box;
    public Bee(String name,Box box){     
        this.name=name;
        this.box=box;
    }
    public void run(){
        while(true){  
            int n=box.add();
            System.out.println(name+"生产了蜂蜜:1,box:"+n);
        }
    }
}
//熊
class Bear extends Thread{
    private String name;
    private Box box;
    public Bear(String name,Box box){
        this.name=name;
        this.box=box;
    }
    public void run(){
        while(true){
            box.remove();
            System.out.println(name+"吃掉了蜂蜜:20 ");
        }
    }
}
//蜜罐
class Box{
    private int  MAX=20;
    private int count;
    //添加蜂蜜加1
    public synchronized int add(){
        while(count>=MAX){             //这里只能用while而不能用if,因为if只执行一次,而while要求每次都要重新判断
            try{
                this.notify();    //当蜜罐里的蜂蜜达到最大值20时,蜜蜂就通知熊取蜂蜜
                this.wait();      //蜜蜂线程进入等待队列
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        return ++count;

    }
    //移出蜂蜜-MAX
    public synchronized void remove(){
        while(count<MAX){
            try{
                this.wait();    //当蜜罐里的蜂蜜不足20时,熊处在等待队列
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
        count=0;
        this.notify();      //熊取完蜂蜜后,通知蜜蜂继续生产蜂蜜


    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值