If you want to pause (temporarily cease) a particular thread in Java from executing, you can make use of the sleep() static method from the Thread class from java.lang package.
When you peek into the java.lang.Thread class, you will see that you have three overloaded sleep() methods to choose from.
public static void sleep(long millis) throws InterruptedException
public static void sleep(long millis, int nanos) throws InterruptedException
public static void sleep(Duration duration) throws InterruptedException
Some key points to make a note about the sleep methods.
- They are static methods, hence belong to the class and are invoked using
Thread.sleep()
. - They do not return any value (void).
- Throws a InterruptedException.
Let's take a look at each of them one-by-one with examples.
1. sleep(long millis)
You can make use of the method to make the currently executing thread sleep for the provided time as milliseconds.
Example 1: Make current Thread sleep for 1000ms = 1 second
public class ThreadSleepExample {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(1000);
System.out.println("I just slept for a second!");
}
}
In the above example, we made the main thread to sleep for 1000ms.
Example 2: A negative timeout value = IllegalArgumentException
Note: If you try to add a negative long value, you will get a IllegalArgumentException saying "timeout value is negative".
public class ThreadSleepExample {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(-100);
}
}
The max value you can provide is the max value of long which is 9223372036854775807. I am sure there is no use case that needs more time as long max value turns out to be ~290 million years!
Any value above this value may cause an underflow and thus IllegalArgumentException with a negative value.
2. sleep(long millis, int nanos)
If you are working with a system where you need to make use of the sleep method for a very short time with high precision then you should make use of this method.
Some use-case could be real-time or high-frequency trading systems or IOT applications.
Example 3:
Thread.sleep(10, 12);
Note that the second parameter to this method is of type int yet the allowed range is 0-999999, outside this range will result in IllegalArgumentException.
Thread.sleep(10, -12);
3. void sleep(Duration duration)
This method was added in the Java JDK 19 version. You can make use of the time-based Duration class with time values such as '54.2 seconds'. This method is no-operation (no-op) if the provided duration is negative. The max value of the duration can be MAX_VALUE should be less than 292 years.
Builder Methods from Duration class.
of (long amount, TemporalUnit unit)
ofMillis (long millis)
ofNanos (long nanos)
ofMinutes (long minutes)
ofDays (long days)
ofHours (long hours)
ofSeconds (long seconds)
ofSeconds (long seconds, long nanoAdjustment)
Example 4:
System.out.println("Sleeping for 20 mins...");
Thread.sleep(Duration.ofMinutes(20));
Example of InterruptedException:
InterruptedException is thrown when a thread that is in a waiting or sleeping state gets interrupted, either before or during its activity.
Example 5:
public class InterruptThreadSleepMethodExample {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(10000); //10 seconds
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("t1 thread interrupted!!");
}
});
t1.start();
try {
Thread.sleep(4000);
t1.interrupt(); //Interrupt t1 thread
} catch (InterruptedException e) {
System.out.println("Main thread interrupted!");
}
}
}
Take-aways:
- Thread.sleep() is a simple way to introduce delays without being busy waiting.
- You can choose from the 3 overloaded sleep() methods from the Java Thread class.
- Sleep duration is specified in milliseconds, nanoseconds, or using a Duration object.
- When the thread is sleeping, it doesn't consume CPU resources.
- Sub-millisecond precision is achievable with Thread.sleep(long millis, int nanos), though the accuracy may be challenging in real-time systems due to system-specific variations.
- Throws InterruptedException when interrupted.
Facing issues? Have Questions? Post them here! I am happy to answer!
Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.
Follow him on: X
You can also reach out to him via e-mail: rakesh@code2care.org
- Get the current timestamp in Java
- Java Stream with Multiple Filters Example
- Java SE JDBC with Prepared Statement Parameterized Select Example
- Fix: UnsupportedClassVersionError: Unsupported major.minor version 63.0
- [Fix] Java Exception with Lambda - Cannot invoke because object is null
- 7 deadly java.lang.OutOfMemoryError in Java Programming
- How to Calculate the SHA Hash Value of a File in Java
- Java JDBC Connection with Database using SSL (https) URL
- How to Add/Subtract Days to the Current Date in Java
- Create Nested Directories using Java Code
- Spring Boot: JDBCTemplate BatchUpdate Update Query Example
- What is CA FE BA BE 00 00 00 3D in Java Class Bytecode
- Save Java Object as JSON file using Jackson Library
- Adding Custom ASCII Text Banner in Spring Boot Application
- [Fix] Java: Type argument cannot be of primitive type generics
- List of New Features in Java 11 (JEPs)
- Java: How to Add two Maps with example
- Java JDBC Transition Management using PreparedStatement Examples
- Understanding and Handling NullPointerException in Java: Tips and Tricks for Effective Debugging
- Steps of working with Stored Procedures using JDBCTemplate Spring Boot
- Java 8 java.util.Function and BiFunction Examples
- The Motivation Behind Generics in Java Programming
- Get Current Local Date and Time using Java 8 DateTime API
- Java: Convert Char to ASCII
- Deep Dive: Why avoid java.util.Date and Calendar Classes
- Column Mode Editing in Notepad++ - NotepadPlusPlus
- Find MAC address of your laptop device - HowTos
- How to Disable Remote Management using Mac Terminal - MacOS
- MySQL Workbench - Connection Warning - Incompatible/nonstandard server version or connection protocol detected - MySQL
- List of 28 Protocols supported by cURL with Examples - cURL
- Calculate Volume of Cylinder - C-Program
- Android M cannot run app using play button : Android Studio - Android
- MacBook - Time Limit - You have reached your time limit, Ignore Limit - MacOS