Hi
I saw the above responses and they seem to be correct to me though a bit ambiguous. I am putting in my thoughts below on this. Hope it helps.
Since sleep(int) only effects the current Thread it is static. But the simular function in Object is not. Shouldn't wait() be static?
1.wait causes the current thread to wait and give away the lock it holds. That's why wait is always called in a synchronized block on the locking object of this block. When some other thread using the same locking object calls notifyAll, all other threads waiting on this locking object need to be notified. So here you see that the method wait is very specific to the locking object and hence its a non-static method.
2.sleep causes the current thread to just sleep. No giving away of lock is associated. It just frees the processor to do other things otherwise it can be equated to something like an infinite loop. Once sleep is over same thread can continue processing as it still has the lock. Here we see that method sleep is not associted with any object and hence it is static.
According to the API it is not. Then can the method wait() cause another thread of execution to wait? That does not seems to be logical since it's purpose is to cause the current thread to wait until another thread invokes the notify() method.
I do not quite understand your question. wait always blocks the current thread in which it is called and never blocks any other thread.Technically wait() can be called on any object. But it makes sense to call wait() on a locking object. Because if you call wait on just any other object, first of all it will throw IllegalMonitorStateException if you are not doing this from a synchronized block. If you are doint it inside a synchronized block on a object, the current thread goes to an infinite wait until some other thread notifies on tje locking object.
Also wait() throws InterruptedException if another thread has interrupted the current thread. But when will this happen? Does it happen when it receives a notify? And sleep(int) also throws InterruptedException, again how can another thread interrupt the sleep of the current thread?
wait/sleep throw interrupted exception when another thread calls the interrupt method on the thread contaning the wait/sleep method. One important thing to note is that a thread in wait state gets back the lock once it is interrupted.
Try out this code which is an example of the discussion above:
Hope I am clear. Please post your queries on this thread if you find I am wrong or not clear somewhere.