这个内容真是常学常忘啊,这次学了总结一下先:
一、wait、notify和notifyall一定要在synchronized语句块中运行,并且synchronized的对象就是调用wait、notify和notifyall方法的对象。比如说下面这一对就会抛错IllegalMonitorStateException:
synchronized (testObj) {
widgets.notify();
}
synchronized (testObj) {
try {
widgets.wait();
} catch (InterruptedException e) {
}
}
必须是:
synchronized (widgets) {
widgets.notify();
}
synchronized (widgets) {
try {
widgets.wait();
} catch (InterruptedException e) {
}
}
二、用什么对象调用wait,就需要用同样的对象调用notify。
三、多个线程使用同一个对象wait了以后,这些线程都停了,给出去了锁。有锁的那个线程调用一下notify,会随机激活一个刚才用这个对象停了的线程,用别的对象激活的,不算。所以下面这道题,看看选啥:
How can you specify which thread is notified with the wait/notify protocol?
A: Pass the object reference as a parameter to the notify method
B: Pass the method name as a parameter to the notify method
C: Use the notifyAll method and pass the object reference as a parameter
D: The wait/notify protocol does not offer a method of specifying which thread will be notified.
四、如果是用notifyall,那所有使用这个对象停了的线程都被激活了,都去抢锁了。例子可参考下面这个:
http://hi.baidu.com/scuyangl/item/5ca7dc255feaa10176272cca