The sleep method of the Thread class is a
The thread resumes execution from its previous state before the halt once the sleep time is over.
InterruptedException is thrown if another thread interrupts the current thread when it is in sleep mode.
The
Threadclass is defined in thejava.langpackage. Use the import statement below to import theThreadclass.
import java.util.Thread;
There are two variations of this method.
public static void sleep(long millis, int nanos)
long millis: The time in milliseconds for which the thread will sleep.
int nanos: It’s the additional time up to which the thread neds to be in the sleeping mode. The range of n is from to .
The method doesn’t return anything.
public static native void sleep(long millis)
long millis: The time in milliseconds for which the thread will sleep.The method doesn’t return anything.
The non-access modifier
nativeis used to access methods written in languages other than Java, such as C/C++.
In the code below, we use the sleep() method to make the main thread sleep for two seconds.
import java.lang.Thread;class Main {public static void main(String[] args) throws InterruptedException {System.out.println("Sleeping for 2 seconds");Thread.sleep(2000);System.out.println("Sleep Over");}}
In the code below, we declare a class called Temp that extends the Thread class.
The Thread.sleep() method is inside the overridden run() method. Next, an instance of the Temp class is created.
The start() method is used to begin the execution of the run() method.
The Temp thread is interrupted using the method interrupt() on the instance of the Temp class.
import java.lang.Thread;class Main {static class Temp extends Thread {public void run() {try {Thread.sleep(2000);System.out.println("In Temp class");} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {Temp temp = new Temp();temp.start();temp.interrupt();}}