java线程wait(),notifyAll(),为什么会报错啊,帮忙看一下

小虎zzzz 2017-04-10 10:10:33
public class Storage {
private Integer num = new Integer(0);

private static final int MAX_SIZE=100;

//生产
public void produce(int number){
synchronized (num) {
while(num+number>MAX_SIZE){
System.out.println("无法生产,当前仓库存储量:"+num);
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = num+number;
System.out.println("生产了"+number+ " 仓库总量:"+num);
num.notifyAll();
}
}

//消费
public void consume(int number){
synchronized (num) {

while(num<number){
System.out.println("无法消费,仓库存储量不足!"+num);
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num = num-number;
System.out.println("消费了"+number +" 仓库总量:"+num);
num.notifyAll();
}

}


public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}



}


生产了10   仓库总量:10
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.chenxin.生产消费.Storage.produce(Storage.java:21)
at com.chenxin.生产消费.Product.run(Product.java:14)
at java.lang.Thread.run(Thread.java:745)
消费了5 仓库总量:5
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.chenxin.生产消费.Storage.consume(Storage.java:39)
at com.chenxin.生产消费.Consumer.run(Consumer.java:12)
at java.lang.Thread.run(Thread.java:745)
...全文
441 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
soton_dolphin 2017-06-24
  • 打赏
  • 举报
回复
当你声明num是Integer 的时候,num保存的是指向Integer(0)的一个地址, 当你再次赋值给num的时候,它会保存另一个Integer实例的地址,这个实例已经不是当前线程加入wait的那个实例,再用notifyall的时候就找不到当前的线程了
RyanNewLife 2017-06-23
  • 打赏
  • 举报
回复
你这个代码没有贴全。也没有看你实现Runnable接口,也没有继承Thread类。
xiaovhao 2017-04-10
  • 打赏
  • 举报
回复
try { num.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } num = num+number; 你前面用的num锁,但是后面又改变了num,导致唤醒的时候出错
小虎zzzz 2017-04-10
  • 打赏
  • 举报
回复
synchronized(num)不就是同步锁吗?。。
FengRider 2017-04-10
  • 打赏
  • 举报
回复
没加同步锁,你在通知的时候加一下同步锁

synchronized(num){
      num.notifyAll();
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧