Search code examples
javathread-sleep

Why we need to use Thread.sleep() instead Sleep() in Java?


Why we have to use Thread.sleep() instead of just sleep() in Java? What are reason, that forces developers to use "longer" version?


Solution

  • Because sleep() is a static method of Thread. You could import it static, and then use sleep()

    import static java.lang.Thread.sleep;
    public static void main( String[] args )
        {
            try
            {
                sleep( 1000 );
            }
            catch ( InterruptedException e )
            {
                e.printStackTrace();
            }
        }
    

    see here: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

    see also here (https://stackoverflow.com/a/421127/461499) on why to use static imports sparelingly.