java多线程问题求助:wait()和notify()

shihengli2010 2017-07-20 02:27:15
public class Plate {

List<Object> eggs = new ArrayList<Object>();

class GetEgg extends Thread {

public GetEgg(String name){
super(name);
}
@Override
public void run() {
synchronized (eggs) {
while (eggs.size() == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.clear();
notifyAll();
System.out.println("拿到鸡蛋");
}

}
}

class PutEgg extends Thread {

public PutEgg(String name){
super(name);
}

public void run() {
synchronized (eggs) {
while (eggs.size() > 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
eggs.add(new Object());
notifyAll();
System.out.println("放入鸡蛋");
}
}
}

public static void main(String[] args) {

Plate plate = new Plate() ;
for(int i =0 ; i< 10 ; i++){
GetEgg g = plate.new GetEgg("getEgg"+i);
PutEgg p = plate.new PutEgg("petEgg"+i);
g.start();
p.start();
}
}

}

上面代码:PutEgg 线程放鸡蛋,GetEgg 线程要取鸡蛋 ,报错:java.lang.IllegalMonitorStateException
找不到错误的原因,求帮助
...全文
86 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
shihengli2010 2017-07-20
  • 打赏
  • 举报
回复
引用 1 楼 soton_dolphin 的回复:
你synchronized(eggs) 的是egg实例,那么wait(), 和 notifyall() 也应该是应用在eggs上面。 而你的代码wait(), notifyall 是用在this上面,this没有synchronized,所以会报错
高手啊,我将代码改成eggs.notifyAll();eggs.wait() 就能得到结果了,非常感谢
soton_dolphin 2017-07-20
  • 打赏
  • 举报
回复
你synchronized(eggs) 的是egg实例,那么wait(), 和 notifyall() 也应该是应用在eggs上面。 而你的代码wait(), notifyall 是用在this上面,this没有synchronized,所以会报错

62,616

社区成员

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

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