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,会怎么样?

    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?