LiorGolan
LiorGolan

Reputation: 375

Why do we need to lock() before wait()?

In multi-threaded applicatoin;
Why do we need to lock() before we wait()? What could go wrong if we didn't lock()?

Upvotes: 0

Views: 363

Answers (1)

pbajpai
pbajpai

Reputation: 1369

This question is similar to why wait() and notify() method should be called inside synchronized block,because to enter in synchronized block the thread first needs the lock on the object then only It can enter in the block.

wait() and notify() are basically two methods for inter-thread communication, so If a thread want to wait on a object for some condition to be fulfilled before proceeding further, so It can call wait() and then some other thread when fulfilled that condition then that thread will call notify() on the same object to notify the previously waiting thread. Actually Its a very common question. I will suggest you once go through below links, to clear your doubts and make your concept clearer.

  1. http://javarevisited.blogspot.com/2011/05/wait-notify-and-notifyall-in-java.html
  2. Why must wait() always be in synchronized block

Upvotes: 1

Related Questions