Java异常之java.lang.IllegalMonitorStateException
Exception in thread "Thread2" Exception in thread "Thread1" java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at Test.V.run(V.java:9)
at java.lang.Thread.run(Thread.java:748)
java.lang.IllegalMonitorStateException
at java.lang.Object.notifyAll(Native Method)
at Test.V.run(V.java:9)
at java.lang.Thread.run(Thread.java:748)
获取监视器异常
源码如下:
public class V implements Runnable {
static int i=0;
@Override
public void run() {
i=0;
while (i < 100) {
notifyAll();
synchronized (this) {
System.out.println(Thread.currentThread().getName());
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
System.out.println(i);
}
}
return ;
}
public static void main(String[] args) {
V v = new V();
Thread t1 = new Thread(v);
Thread t2 = new Thread(v);
t1.setName("Thread1");
t2.setName("Thread2");
t1.start();
t2.start();
}
}
当你的wait和notify(notify)方法没有放在锁之间的时候,会出现的异常。
源码中是这么注释的
当前的线程不是拥有锁的对象的线程。事实上在调用wait和notify之后,对象就不是同一个对象了,因此在锁外使用会出现该异常