多线程错误wait notifyAll错误
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开始等待
怎么修改