OneZero
OneZero

Reputation: 11914

What is the `Thread` in this Java code?

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]);
        }
    }
}

In this piece of code there's no Thread creation, but does exist Thread.sleep(4000). So what does this Thread represent? The main program itself? In other words, does Thread implicitly the program itself?

Upvotes: 2

Views: 153

Answers (5)

Gray
Gray

Reputation: 116908

does Thread implicitly the program itself?

No. To quote from the Thread.sleep() javadocs:

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

So Thread.sleep() sleeps the currently running thread which happens to the "main" thread which runs the main(...) method.

So what does this Thread represent? The main program itself?

No. Thread is the name of the class. It depends on what static method you are calling about what it does. For most of the per-thread methods however, (sleep(...), yield(), etc.) Thread.method() applied to the current running thread or Thread.currentThread().

Upvotes: 2

rvillablanca
rvillablanca

Reputation: 1646

On every Java program, always exists one Thread at least. The first thread is called 'main'.

Thread.sleep(4000);

Call to the current thread at this moment and it is forced to wait 4000 milliseconds.

You have not created any thread but the Java Virtual machine has created the 'main' thread, responsible to run your program :)

Upvotes: 1

Yes, Thread.sleep() acts on the current thread, which in your case is simply the one thread that always has to exist to run a program.

Upvotes: 5

David Schwartz
David Schwartz

Reputation: 182829

In Java, sleep is a static member function of class Thread that causes the thread that calls it to sleep.

Upvotes: 1

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18148

The static call to sleep causes the currently executing thread to sleep, in this case to simply to pause the output (as opposed to yielding to another thread or whatever)

Upvotes: 0

Related Questions