 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the use of Thread.sleep() method in Java?
The sleep() method is a static method of Thread class and it makes the thread sleep/stop working for a specific amount of time. The sleep() method throws an InterruptedException if a thread is interrupted by other threads, that means Thread.sleep() method must be enclosed within the try and catch blocks or it must be specified with throws clause.
Whenever we call the Thread.sleep() method, it can interact with the thread scheduler to put the current thread to a waiting state for a specific period of time. Once the waiting time is over, the thread changes from waiting state to runnable state.
Syntax
public static void sleep(long milliseconds) public static void sleep(long milliseconds, int nanoseconds)
The sleep(long milliseconds) method makes a thread to sleep for some specific milliseconds only.
The sleep(long milliseconds, int nanoseconds) method makes a thread to sleep for some specific milliseconds plus nanoseconds.
Example
 class UserThread extends Thread { public void run() { for(int i=1; i <= 5; i++) { System.out.println("User Thread"); try { Thread.sleep(1000); // sleep/stop a thread for 1 second } catch(InterruptedException e) { System.out.println("An Excetion occured: " + e); } } } } public class SleepMethodTest { public static void main(String args[]) { UserThread ut = new UserThread(); ut.start(); // to start a thread } }  Output
User Thread User Thread User Thread User Thread User Thread
