我正在阅读关于线程同步和tutorial中的wait / notify结构的内容。它说明:
当调用wait时,线程释放锁并暂停执行。在未来的某个时间,另一个线程将获取相同的锁并调用Object.notifyAll,通知等待该锁的所有线程已发生了重要事件。
在第二个线程释放锁后一段时间,第一个线程重新获取锁并通过从wait调用返回来恢复执行。
据我所知,如果有多个线程在第一个线程被
当调用wait时,线程释放锁并暂停执行。在未来的某个时间,另一个线程将获取相同的锁并调用Object.notifyAll,通知等待该锁的所有线程已发生了重要事件。
在第二个线程释放锁后一段时间,第一个线程重新获取锁并通过从wait调用返回来恢复执行。
据我所知,如果有多个线程在第一个线程被
notify
唤醒时可以竞争锁,则其中任何一个线程都可以获得该对象上的锁。我的问题是,如果这个第一个线程本身重新获取锁,它是否必须从同步方法的开头重新开始(这意味着它再次执行while循环检查wait()条件之前的代码),还是仅在wait()
行处暂停?// Does the waiting thread come back here while trying to own the
// lock (competing with others)?
public synchronized notifyJoy() {
// Some code => Does this piece of code gets executed again then in case
// waiting thread restarts its execution from the method after it is notified?
while (!joy) {
try {
// Does the waiting thread stay here while trying to re-acquire
// the lock?
wait();
} catch(InterruptedException e) {}
}
// Some other code
}
wait
命令中恢复。 - Boris the Spider