leon
leon

Reputation:

Synchronized method in Java

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

Answers (3)

Ovidiu Lupas
Ovidiu Lupas

Reputation: 185

It is also a best practice to wrap wait() invocation in a while . Reason: sporadic wake-up!

Upvotes: 1

sateesh
sateesh

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

nos
nos

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

Related Questions