程序背景: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();
}
}
一个BOX,被那么多对象同时使用,放不下后还wait,会怎么样?
看下你代码里面的共享变量有没有正确的同步,没有同步就会死锁了。
代码在于你的打印语句问题。
System.out.println(this.name + "生产了蜂蜜,总数:" + i);
这行代码是非线程安全的。把他放入add方法中就好了。
--记得给分。另外你程序没有死锁吧
notify改notifyall吧。另外add中的notify移动到while循环外边
--我要分
好多多线程大佬啊。学习了学习了
notify改notifyAll 别的不需要改
notify是随机解锁一个线程,当你的两个熊都wait时 蜜蜂解锁的线程不是bear那么就锁死了 改为notifyAll解锁所有线程 两只熊都会解锁 让两个bear抢线程就无限循环了
因为你锁只有一个,20蜜采完想去notify熊的时候,可能只是唤醒了另一只蜜蜂,然后那个蜜蜂看了到蜜已经20了就又notify了另一只蜜蜂,因为蜜蜂有100只,熊只有两只,所以每次都是只有很低的概率能唤醒熊,导致不停地蜜蜂唤醒蜜蜂,看上去就跟死锁一样,解决办法就是降低蜜蜂数量