How to Use Sleep in Thread Java: Simple Guide
In Java, you use
Thread.sleep(milliseconds) to pause the current thread for a specified time. This method throws InterruptedException, so you must handle it with a try-catch block.Syntax
The Thread.sleep() method pauses the current thread for a given number of milliseconds. It requires a long value representing the sleep duration in milliseconds. Because it can be interrupted, it must be called inside a try-catch block to handle InterruptedException.
java
try { Thread.sleep(1000); // Sleep for 1000 milliseconds (1 second) } catch (InterruptedException e) { e.printStackTrace(); }
Example
This example shows a thread printing numbers from 1 to 5 with a 1-second pause between each print using Thread.sleep(). It demonstrates how to pause execution safely.
java
public class SleepExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); try { Thread.sleep(1000); // Pause for 1 second } catch (InterruptedException e) { System.out.println("Sleep interrupted"); Thread.currentThread().interrupt(); // Restore interrupt status } } System.out.println("Done counting."); } }
Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done counting.
Common Pitfalls
- Forgetting to handle
InterruptedExceptioncauses compilation errors. - Calling
Thread.sleep()outside a try-catch block is invalid. - Ignoring the interrupt by not restoring the thread's interrupt status can cause issues in multi-threaded programs.
- Using
sleepdoes not release locks or resources held by the thread.
java
/* Wrong way: Missing try-catch */ // Thread.sleep(1000); // This causes a compile error /* Right way: Handle InterruptedException */ try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Good practice to restore interrupt }
Quick Reference
| Method | Description |
|---|---|
| Thread.sleep(long millis) | Pauses current thread for specified milliseconds |
| Thread.sleep(long millis, int nanos) | Pauses current thread for millis plus nanos nanoseconds |
| InterruptedException | Exception thrown if thread is interrupted during sleep |
Key Takeaways
Use Thread.sleep(milliseconds) inside a try-catch block to pause a thread.
Always handle InterruptedException to avoid compile errors and manage interrupts properly.
Sleeping a thread pauses only that thread; it does not release locks or resources.
Restore the interrupt status if catching InterruptedException to respect thread interruption.
Thread.sleep accepts milliseconds and optionally nanoseconds for precise timing.