notify()调用的位置重要吗?(Java) [英] Does the position of the notify() call matter?(Java)
问题描述
假设我有以下情况:
synchronized void someMethod() {
...
try {
wait();
}catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
...
}
和
synchronized void someOtherMethod() {
...
notify();
}
Thread
首先访问someMethod
,进入wait
,然后someOtherMethod
通知它并返回到Runnable
状态. notify()
调用在方法中的位置重要吗?即使将notify()
调用放置在方法内部的不同位置,我也没有注意到行为的变化.
And the Thread
accesses first someMethod
, goes into wait
and then someOtherMethod
notifies it and returns to Runnable
state. Does the position of the notify()
call in the method matter? I noticed no change in behavior even when I positioned the notify()
call at different positions inside the method.
调用notify()
时是否应立即通知Thread
?
Shouldn't the Thread
be notified immediately when the call to notify()
is made?
推荐答案
synchronized
块中notify()
调用的位置没关系无关紧要,因为根据定义,如果您仍在synchronized
块,然后您仍然按住该锁.
The position of the notify()
call within the synchronized
block does not matter because by definition, if you are still in the synchronized
block, then you still hold the lock.
在调用notify()时是否应立即通知线程?
Shouldn't the Thread be notified immediately when the call to notify() is made?
是的.调用notify()
会将来自等待队列(等待条件)的线程(如果有)放入阻塞队列(等待锁).这确实会立即发生,但是被唤醒的线程需要获得锁才能开始运行.因此它立即被移出了等待队列,但仍在等待获取锁.
Yes. Calling notify()
puts one of the threads (if any) from the wait queue (waiting for the condition) into the blocked queue (waiting for the lock). This does happen immediately, but the awoken thread needs to get the lock before it can start running. So it is immediately moved out of the wait queue but is still waiting to get the lock.
顺便说一句,我建议将其写为this.wait()
和this.notify()
只是为了明确指出受影响的对象.
Btw, I would recommend writing this as this.wait()
and this.notify()
just to be explicit about which object is being affected.
这篇关于notify()调用的位置重要吗?(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!