Thread class:
public static native void sleep(long millis) throws InterruptedException
Thread.sleep(1000); β pauses execution for 1 second.
InterruptedException if another thread interrupts the current thread while sleeping.
public static void sleep(long millis, int nanos) throws InterruptedException
sleep(long millis) method after adjusting the value of millis based on the nanos parameter.
millis = number of milliseconds, nanos = additional time in nanoseconds (0β999999).
InterruptedException if interrupted while sleeping.
public class SleepExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
System.out.println(i);
try
{
Thread.sleep(1000); // Pause for 1 second
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
1 2 3 4 5
sleep() is a static method of the Thread class.InterruptedException, so it must be handled using try-catch or declared with throws.sleep(); passing them will throw IllegalArgumentException.sleep() method is declared as native, meaning its implementation is provided in another language (like C/C++) within the JVM.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.