0

I am currently learning Java. As soon as I got to the point where Threads were included in the lessons I wondered why Thread.sleep() can be called in the main method.

Idea: The Thread class is static, that is why it doesn`t need to be instantiated. But I wonder why I can create an object of it. How can I understand that?

Short code snippet:

class MyClass{
    public static void main(String [] args){
        Thread trd  = new Thread(new MyThread());
        trd.start();

        try{
            Thread.sleep(1000);
        }
       catch (InterruptedException e) {
            System.out.println("Error occured");
        }
    }
}

public class SuperClass{
    int x = 5;
}

public class MyThread extends SuperClass implements Runnable{
    public void run(){
        while(x<10){
            System.out.println("Hello" + x);
            x++;
        }
    }
}
Alan
  • 589
  • 5
  • 29

2 Answers2

4

The Thread class itself isn't static, as you can see in the Java docs for java.lang.Thread:

public class Thread extends Object implements Runnable

When a call like Thread.sleep is possible (so without creating an instance of a Thread object), it means the method sleep is static in this case:

public static void sleep(long millis) throws InterruptedException


Here a simply example class to illustrate how the static vs non-static methods work a bit more:

public class TestObj{
  public static void staticPrint(){
    System.out.println("Static method call");
  }

  public void regularPrint(){
    System.out.println("Non-static method call");
  }
}

We now can have a call like this:

TestObj.staticPrint();

But when we try the following it will give a compiler error (non-static method regularPrint() cannot be referenced from a static context):

TestObj.regularPrint();

Instead, you should create an instance in order to call the regularPrint method:

TestObj testObjInstance = new TestObj();
testObjInstance.regularPrint();

Note that it is still possible to call static methods with the instance, although it will give a warning (The static method staticPrint() from the type TestObj should be accessed in a static way):

testObjInstance.staticPrint();

Try it online.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
1

The top level class can't be static only inner can .

your question is about why sleep method defined in class java.lang.Thread is static .

answer : u can call it anywhere in your code without have a reference to your thread.

sleep Causes the currently executing thread to sleep (current = thread where it's called)

Zeuzif
  • 318
  • 2
  • 14