Tarun Oohri wrote:Hello everybody,
I have been studying threads but couldn't understand the followings :
Q1. Why methods like wait, notify, notifyall are of Object class but not of Thread class ?
This gets asked a lot. Look at this FAQ:
https://coderanch.com/how-to/java/WaitAndNotifyInObjectClass
Q2. Why sleep() is static ?
This helps when you properly separate the task to be run from the Thread instance it is run in. Most code that you execute will not be written in a class that extends Thread, so it won't have direct access to the Thread object in which it runs. That means if sleep() were non-static the code which wanted to execute sleep() would have to get a reference to the Thread in which it is running. It could do so by calling the static Thread#currentThread() method. So the code would look like:
Thread.currentThread().sleep();. Since this would be the 'normal' case, why make the user always call currentThread()? Especially considering it would give the false impression that you could call sleep() on an arbitrary Thread object (which you can't)? So, to prevent the extra method call, and to make it clear that you can't call sleep() on any Thread other than the current one (by not providing an API that allows it) Thread#sleep() is static.