Java: why Thread.sleep() and yield() are static?

后端 未结 6 382
庸人自扰
庸人自扰 2021-01-03 19:56

Why sleep() and yield() methods are defined as static methods in java.lang.Thread class?

相关标签:
6条回答
  • 2021-01-03 20:39

    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.

    0 讨论(0)
  • 2021-01-03 20:42

    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?

    0 讨论(0)
  • 2021-01-03 20:51

    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

    0 讨论(0)
  • 2021-01-03 20:53

    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.

    0 讨论(0)
  • 2021-01-03 20:56

    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");
        } 
    
    }
    
    0 讨论(0)
  • 2021-01-03 21:02

    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

    0 讨论(0)
提交回复
热议问题