qq_34179872 2017-11-05 08:10 采纳率: 0%
浏览 913
已结题

求问这个程序哪里导致多线程死锁了????

程序背景:100只蜜蜂生产蜂蜜,每次生产1,两只熊消耗蜂蜜,每次消耗20,
生产的蜂蜜放在Box中,最大容量为20。

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

class Bee extends Thread{
    private String name;
    private Box box;

    public Bee(String name, Box b){
        this.name = name;
        this.box = b;
    }

    public void run(){
        while(true){
            int i = box.add();  
            System.out.println(this.name + "生产了蜂蜜,总数:" + i);
        }
    }
}

class Bear extends Thread{
    private String name;
    private Box box;

    public Bear(String name, Box b){
        this.name = name;
        this.box = b;
    }

    public void run(){
        while(true){
            box.remove();   
            System.out.println(this.name + "消耗了蜂");
        }
    }
}

class Box{
    private final int Max = 20;
    private int count = 0;

    public synchronized int add(){
        while(count >= Max){
            try{
                this.notify(); //方法执行完后释放锁旗标。
                this.wait();   //立即释放锁旗标。
            }
            catch(Exception e){
            }
        }
        return ++count;
    }

    public synchronized void remove(){
        while(count < Max){
            try{
                this.wait();
            }
            catch(Exception e){
            }
        }
        count = 0;
        this.notify();
    }
}
  • 写回答

8条回答 默认 最新

  • 云外缘 2017-11-05 09:49
    关注

    一个BOX,被那么多对象同时使用,放不下后还wait,会怎么样?

    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况