提倡的范例是 wait() 应该在同步块(synchronized block)内的 while 循环内调用。
我的问题是 waiting() 线程如何取回锁?
// Thread 1
synchronized (mon) {
while (!condition)
mon.wait();
// Do something
}
//Thread 2
synchronized (mon) {//set condition appropriately
mon.notify();
}
考虑线程 1 首先运行并开始等待条件。它释放锁,线程 2 获得锁设置条件并通知线程 1。现在线程 1 获得锁,检查条件并开始执行“做某事”。
我的问题是,当通知线程 1 它从 while 条件开始执行时,具有 Synchronized(mon) 的代码行再也不会执行,那么线程 1 如何获取锁?将锁返回给线程 1 的内部动力是什么?
最佳答案
当 Thread1 被通知线程必须在退出等待方法之前获取锁,请参阅 Object#wait 的 java 文档:
The thread
T
is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object; once it has gained control of the object, all its synchronization claims on the object are restored to the status quo ante - that is, to the situation as of the time that thewait
method was invoked. ThreadT
then returns from the invocation of thewait
method. Thus, on return from thewait
method, the synchronization state of the object and of threadT
is exactly as it was when thewait
method was invoked.
关于java - wait() 如何在 Java 中取回锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760513/