Reputation:
I have a question. In the following code, if a thread were blocked at wait statement, and another thread attempts to execute foo(), would the hello world message be printed? and Why?
synchronized foo(){
system.out.println("hello world");
.....
wait();
.....
}
Upvotes: 1
Views: 537
Reputation: 185
It is also a best practice to wrap wait() invocation in a while . Reason: sporadic wake-up!
Upvotes: 1
Reputation: 28713
For a thread to enter the method foo
it needs to have a lock on the object (monitor) which contains the foo method. When the wait
is executed the thread releases the lock on the monitor. So if another thread attempts to execute foo and (say it could acquire the lock) then it would print the "hello world" message.
Upvotes: 3
Reputation: 229294
Yes.
wait(); gives up the monitor, so yes , if Thread A is blocked in wait(); , Thread B would be able to enter foo and print hello world
Upvotes: 1