我们能调用wait()的唯一地方是在一个同步的方法或代码块内部。若在一个不同步的方法内调用wait()或者notify(),尽管程序仍然会编译,但在运行它的时候,就会得到一个IllegalMonitorStateException(非法监视器状态违例),而且会出现多少有点莫名其妙的一条消息:“current thread not owner”(当前线程不是所有人”。注意sleep(),suspend()以及resume()都能在不同步的方法内调用,因为它们不需要对锁定进行操作。)
class ThreadTest extends Thread { boolean tag = false; int count = 0; public void setWait(boolean w) { tag = w; } public synchronized void run() { while (true) { if (tag) { try { wait(); } catch (Exception e) { e.printStackTrace(); } } else { try { notify(); } catch (Exception e) { e.printStackTrace(); } } System.out.println(count); count++; if (count == 11) { break; } } } }
boolean tag = false;
int count = 0;
public void setWait(boolean w) {
tag = w;
} public synchronized void run() {
while (true) {
if (tag) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
notify();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(count);
count++;
if (count == 11) {
break;
}
}
}
}