嗨寫了一個示例程序來測試在java中等待的行爲。非法監視器狀態當兩個花等待時異常
我實現Runnable接口的:
class ThreadWait implements Runnable {
Object lock = new Object();
ThreadWait(Object lock){
this.lock = lock;
}
@Override
public void run() {
try {
synchronized (lock){
System.out.println("Started : "+Thread.currentThread().getName());
wait();
System.out.println("Completed : "+Thread.currentThread().getName());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
使用中我main
像:
Object lock = new Object();
ThreadWait t1 = new ThreadWait(lock);
ThreadWait t2 = new ThreadWait(lock);
Thread a= new Thread(t1);
a.setName("A");
Thread b= new Thread(t2);
b.setName("B");
a.start();
b.start();
運行這個程序,我得到這個異常:
Exception in thread "A" Exception in thread "B" java.lang.IllegalMonitorStateException
Started : A
at java.lang.Object.wait(Native Method)
Started : B
at java.lang.Object.wait(Object.java:502)
at ThreadWait.run(SynchronizedExample.java:34)
at java.lang.Thread.run(Thread.java:745)
java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at ThreadWait.run(SynchronizedExample.java:34)
at java.lang.Thread.run(Thread.java:745)
'lock.wait()'...? – MadProgrammer