Last Updated : 23 Jul, 2025
Thread class contains the sleep() method. There are two overloaded methods of sleep() method present in Thread Class, one is with one argument and another one is with two arguments. The sleep() method is used to stop the execution of the current thread (whichever might be executing in the system) for a specific duration of time and after that time duration is over, the thread which is executing earlier starts to execute again.
SyntaxThere are 2 variations of the sleep() method in Java Thread. These are:
public static void sleep(long millis)
public static void sleep(long millis, int nanos)
Parameters:
Exceptions: InterruptedException, IllegalArguementException
Important Points:
We can use Thread.sleep() method for any thread, i.e., we can do it with the main thread or any other thread that we make programmatically.
Example 1: Using Thread.sleep() Method for Main Thread
Java
// Sleeping the main thread
import java.io.*;
import java.lang.Thread;
class Geeks
{
public static void main(String[] args)
{
// we use throws keyword followed by exception
// name for throwing the exception
try {
for (int i = 0; i < 5; i++) {
// sleep the main thread for 1 sec
// for every loop runs
Thread.sleep(1000);
// printing the value of the variable
System.out.print(i+" ");
}
}
catch (Exception e) {
// catching the exception
System.out.println(e);
}
}
}
Output:
0 1 2 3 4
Example 2: Using Thread.sleep() method for Custom thread
Java
// Sleeping the Custom Thread
import java.lang.Thread;
// Class extending the Thread Class
class MyThread extends Thread
{
// Overriding the run method
@Override
public void run()
{
// use throws keyword followed by exception
// name for throwing the exception
try {
for (int i = 0; i < 5; i++) {
// method will sleep the thread
Thread.sleep(1000);
// printing the value of the variable
System.out.print(i+" ");
}
}
catch (Exception e) {
// catching the exception
System.out.println(e);
}
}
public static void main(String[] args)
{
// created thread
MyThread obj = new MyThread();
obj.start();
}
}
Output:
0 1 2 3 4
Example 3: IllegalArguementException when sleep time is Negative
Java
// Showing how exception can occur if we
// pass the negative timeout value.
import java.lang.Thread;
class Geeks
{
public static void main(String[] args)
{
// Use throws keyword followed by exception
// name for throwing the exception
try {
for (int i = 0; i < 5; i++) {
// this will throw the
// IllegalArgumentException
Thread.sleep(-100);
// Printing the value of the variable
System.out.println(i);
}
}
catch (Exception e) {
// Catching the exception
System.out.println(e);
}
}
}
java.lang.IllegalArgumentException: timeout value is negative
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4