Interview Questions

What is significance of sleep() method in detail, what state does it put thread in ?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

29.What is significance of sleep() method in detail, what state does it put thread in ?

sleep() is a native method, it’s implementation is provided by JVM.

10 salient features of sleep() method >
Definition : sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Ex- Thread.sleep(10) causes currently executing thread to sleep for 10 millisec.

Thread state : when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.

Exception : sleep() method must catch or throw compile time exception i.e. InterruptedException.

Waiting time : sleep() method have got few options.
sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
public static native void sleep(long millis) throws InterruptedException;
sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
public static native void sleep(long millis,int nanos) throws InterruptedException;
static method : sleep() is a static method, causes the currently executing thread to sleep for the specified number of milliseconds.
Native method : implementation of sleep() method is provided by JVM.
Let’s see definition of yield() method as given in java.lang.Thread - public static native void sleep(long millis) throws InterruptedException;
Belongs to which class : sleep() method belongs to java.lang.Thread class.
synchronized block : thread need not to to acquire object lock before calling sleep() method i.e. sleep() method can be called from outside synchronized block.

(Continued on next question...)

Other Interview Questions