• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Monitors?

 
prabhu peruka
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not clear with the difference between the wait() and sleep() methods. What is a monitor? all i know is its not a method or any code.
Can anyone help me with that

Thanks in advance!!
 
Georg Nieuwoudt
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sleep() --> if you use sleep for lets say 3 secs, then the currentThread running wil actually do nothing for 3 secs and in that 3 secs the code will go on executing...

wait() --> if you use wait for lets say 3 secs, then the currentThread running will pause all processing for 3 secs then resume with the remaining code...
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure what Georg is trying to say, but it doesn't sound correct to me.

A "monitor" is also (with subtly different meanings) sometimes called a "lock" or a "semaphore" or a "critical section." The basic idea is that if a thread "holds the monitor" for an object, then that thread has special privileges with respect to that object. In particular, the thread that holds the monitor for an object is allowed to execute the code inside that object's synchronized methods, or blocks of code that are marked as synchronized on that object.

Both wait() and sleep() pause for some period of time, and during that time, the calling thread -- and only the calling thread -- pauses and does no further processing. Any other running threads continue on unaffected, except as described below.

If a thread holds the monitor for an object, then calls sleep(), that thread retains the monitor for the object during the pause. That means that while it is sleeping, no other thread can get those special privileges with respect to that one object. This may result in other threads pausing as well, as they are forced to wait for the monitor to be freed at some time in the future.

A thread can only call wait() on an object whose monitor it currently holds. When wait() is called, the monitor is released, and other threads can then hold it. The call to wait() won't return until the monitor is free again, and, optionally, some other thread holding the monitor has called notify() on that object (optionally, meaning that wait() can return without notify if the variant with the time-out argument is used.)

I hope this helped. You can learn more about this material in Sun's threads tutorial at http://java.sun.com/docs/books/tutorial/essential/threads/index.html .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic