多线程错误wait notifyAll错误

teddy9393 2014-08-13 02:34:16
package com.xiaonei2shou.test.llThread;

import java.util.LinkedList;

public class ThreadTest {
private static LinkedList<Boolean> booleanList = new LinkedList<Boolean>();
private static boolean[] needWait = { true };
static {
if (booleanList.size() <= 0) {
for (int i = 0; i < 1000; i++) {
booleanList.add(false);
}
}
}

class OperateThread extends Thread {
public OperateThread(String name) {
super(name);
}

public void run() {
synchronized (needWait) {
while (!booleanList.getFirst()) {
System.out.println(getName() + "开始执行");
if (needWait[0]) {
System.out.println(getName() + "开始等待");
try {
needWait.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(getName() + "结束等待");
}
needWait[0] = true;
Boolean nowBoolean = booleanList.getFirst();
booleanList.removeFirst();
needWait[0] = false;
needWait.notifyAll();
booleanList.addLast(!nowBoolean);
System.out.println(getName() + "结束执行");
}

}
}
}

public static void main(String[] args) {
ThreadTest t = new ThreadTest();
Thread t1 = t.new OperateThread("线程1");
Thread t2 = t.new OperateThread("线程2");
Thread t3 = t.new OperateThread("线程3");
t1.start();
t2.start();
t3.start();
needWait.notifyAll();
while (true) {
if (!t1.isAlive() && !t2.isAlive() && !t3.isAlive()) {
System.out.println(booleanList.size());
System.out.println(booleanList);
break;
}
}
}
}


报错了

Exception in thread "main" 线程1开始执行
线程1开始等待java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at com.xiaonei2shou.test.llThread.ThreadTest.main(ThreadTest.java:55)


线程3开始执行
线程3开始等待
线程2开始执行
线程2开始等待

怎么修改

...全文
211 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
dokia123 2014-08-18
  • 打赏
  • 举报
回复
引用 3 楼 ldh911 的回复:
要对某对象执行 wait 或 notify,必须在该对象的 synchronized 块内。
大神,我发了个问题贴,帮我看看,解解疑。
skgary 2014-08-17
  • 打赏
  • 举报
回复
引用 4 楼 xiaopeipei2004 的回复:
顶顶,脑子不灵了,看这一大段看不进去。。
直接看异常就好了,这个问题比较初级。
grapepaul 2014-08-16
  • 打赏
  • 举报
回复
顶顶,脑子不灵了,看这一大段看不进去。。
MiceRice 2014-08-13
  • 打赏
  • 举报
回复
要对某对象执行 wait 或 notify,必须在该对象的 synchronized 块内。
skgary 2014-08-13
  • 打赏
  • 举报
回复
synchronized (needWait){ needWait.notifyAll(); }
业余草 2014-08-13
  • 打赏
  • 举报
回复
这个只能顶你了,不太懂!!

25,985

社区成员

发帖
与我相关
我的任务
社区描述
高性能WEB开发
社区管理员
  • 高性能WEB开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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