Where does the thread execution begin when it is n

2019-07-02 00:31发布

问题:

public  void add(int num)
{
 synchronized(myObject){
 // line 1
 //line 2
 while(!condition)
 {
  myObject.wait();
  //line 3
 }    
 //line 4
 //line 5
 //line 6
 }
}

When a thread T (waiting for lock on myObject) is notified,
where does T start its execution, at line line 1 or line 3? Thanks.

回答1:

The notified thread needs to re-acquire the lock, but that re-acquisition happens within the call to wait and the thread has the lock once it returns from the wait method, then it starts executing at line 3. Peter's answer is correct (+1).

The javadoc for wait supports this, it says:

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 the wait method was invoked. Thread T then returns from the invocation of the wait method. Thus, on return from the wait method, the synchronization state of the object and of thread T is exactly as it was when the wait method was invoked.

You can test this. If the thread had to start over at the top of the block then you could get by with an if test to check the condition, because once the thread was notified it would still have to make it past the condition test. If the thread picks up where it left off you need the while loop, because the thread needs to check that the condition that made it have to wait is not still true. If you replace the while loop with an if statement and run a multi-threaded test (for instance, you could create a queue, a homegrown one where you can tamper with its put and take methods, with multiple producers and consumers where the consumers are waiting for the queue to be non-empty) then you should be able to see cases where the thread waits, then proceeds even though the condition shouldn't let it (resulting in trying to take something from an empty queue).



回答2:

It is at line 3, thread execution is linear, it
cannot go back, or jump to somewhere just like that.