What is Thread.sleep() in Java?

The sleep method of the Thread class is a staticthe methods in Java that can be called without creating an object of the class. method that is used to halt the working of the current thread for a specified amount of time.

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 Thread class is defined in the java.lang package. Use the import statement below to import the Thread class.


import java.util.Thread;

There are two variations of this method.

Variation 1

Syntax


public static void sleep(long millis, int nanos)

Parameters

  • 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 00 to 999999999999.

Return value

The method doesn’t return anything.

Variation 2

Syntax


public static native void sleep(long millis)

Parameters

  • long millis: The time in milliseconds for which the thread will sleep.

Return value

The method doesn’t return anything.


The non-access modifier native is used to access methods written in languages other than Java, such as C/C++.

Code

Example 1

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");
}
}

Example 2

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();
}
}

Free Resources