Why we have to use Thread.sleep()
instead of just sleep()
in Java? What are reason, that forces developers to use "longer" version?
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.
Java is an object oriented language - every method ("function") must belong to a class, even if it's a static
method (consider, eg, that there's no "global" print
function - you must call System.out.print
). If it really annoys you, though, you could statically import the method:
import static java.lang.Thread.sleep
public class MyClass {
public static void main (String[] args) {
sleep (10);
}
}
sleep()
method in Thread
class is a static
method. We don't access static
methods using the instance object.
Both the this.sleep()
and Thread.sleep()
are the same but it's against the conventions.
static
keyword means it's common to all the classes there for if you use an instance variable to access a static
method it's not clear.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.