类 IllegalMonitorStateException
官方给出的解释是:
抛出的异常表明某一线程已经试图等待对象的监视器,或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。
如下代码抛出异常.
new Thread(){
@Override
public void run() {
if (list.size() == 0) {
synchronized (list) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
list.remove(0);
System.out.println(list);
list.notify();
}
}.start();
解决方法是:要用synchronized锁住对象,确保代码段不会被多个线程调用。
public void run() {
synchronized (list) {
if (list.size() == 0) {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.remove(0);
System.out.println(list);
list.notify();
}
}
}.start();