Why sleep()
and yield()
methods are defined as static
methods in java.lang.Thread
class
?
This is because whenever you are calling these methods, those are applied on the same thread that is running.
You can't tell another thread to perform some operation like, sleep()
or wait
. All the operation are performed on the thread which is being executed currently.
The same reason is why stop() and suspend() methods are deprecated. Intrusion in thread's state from outside is dangerous and can cause unpredictable result. And if sleep is not static, for example, how do you think interruption from it will happen?
They are static so that overriding concept can be avoided i.e.
When they are called with parent class reference to hold child class object like situation it implements Method Hiding concept and not overriding due to Static method nature, i.e parent class(here thread class) method will run which have the complete functionality of sleep and yield.
http://i.stack.imgur.com/goygW.jpg
The code would only execute when someXThread
was executing, in which case telling someYThread
to yield would be pointless. So since the only thread worth calling yield
on is the current thread, they make the method static
so you won't waste time trying to call yield
on some other thread.
Both sleep and yield methods are native. To understand better from above answers I made two classes ClassA and ClassB with same static method. I invoked method of other class to check its behavior. So we can call other class' static method.
So may be there is other reason behind making sleep method static.
public class ClassA {
public static void method(){
System.out.println("Inside ClassA method");
}
public static void main(String[] args) {
method();
ClassB classb = new ClassB();
classb.method();
}
}
public class ClassB {
public static void method(){
System.out.println("Inside ClassB method");
}
}
If you call the yield
or sleep
method, it applies to whichever thread is currently executing, rather than any specific thread - you don't have to specify which thread is currently running to free up the processor.
similar thread in this forum