Tadele Ayelegn
Tadele Ayelegn

Reputation: 4706

how come Thread class called inside another class?

Is it possible to use the Thread class in another class without implementing Runnable interface or without extending the the Thread class itself?

Here is a code that invokes the sleep method on Thread.

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

Upvotes: 1

Views: 1350

Answers (3)

TheLostMind
TheLostMind

Reputation: 36304

sleep() is a static method in class Thread. When you call Thread.sleep(), the current thread is used. So, yes, at any point of time, an executing program should have at least one active/running thread. Calling Thread.sleep() will make the Current Thread sleep. Here, you are not creating a new thread. You are actually using an existing thread. You need to either extend Thread class or implement Runnable for your Custom class to behave as a Thread.

Upvotes: 0

Vince
Vince

Reputation: 15146

You can create an instace of Thread pass a Runnable to it instead of implementing: (Java 8)

Thread thread = new Thread(() -> {
       //code here
});

public class SleepMessages {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            public void run() {
                String importantInfo[] = {
                    "Mares eat oats",
                    "Does eat oats",
                    "Little lambs eat ivy",
                    "A kid will eat ivy too"
                };

                for (int i = 0; i < importantInfo.length; i++) {
                    //Pause for 4 seconds
                    Thread.sleep(4000);
                    //Print a message
                    System.out.println(importantInfo[i]);
                }
            }
        });

        thread.start();
    }            
}

Upvotes: 0

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

Yes it is possible, your code is a proof of this. You can always use static members of a given class without instanciating the class. Roughly, in Java every class is an object that you don't have to instanciate, on which you can call its static methods.

What you can't do is to create a useful Thread without implementing the Runnable interface or extending the Thread class. (You can create a Thread without doing so by instanciating the Thread class directly, but such a thread will not be useful).

Upvotes: 3

Related Questions