Reputation: 11914
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
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
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
Reputation: 6308
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
Reputation: 182829
In Java, sleep is a static member function of class Thread that causes the thread that calls it to sleep.
Upvotes: 1
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