In Java, the Thread.sleep
method is used to pause the current thread for a specified number of milliseconds. It is often used to introduce delays or pause the execution of a thread for a certain period of time.
Here's an example of how you can use the Thread.sleep
method in Java:
Thread.sleep(1000); // pause the current thread for 1 second (1000 milliseconds)
The Thread.sleep
method can throw a InterruptedException
if the thread is interrupted while it is sleeping. Therefore, it is generally recommended to handle this exception in a try-catch
block or to declare that your method throws the exception.
Here's an example of how you can use the Thread.sleep
method and handle the InterruptedException
:
try { Thread.sleep(1000); // pause the current thread for 1 second (1000 milliseconds) } catch (InterruptedException e) { // handle the exception }
It's important to note that the Thread.sleep
method is a static method of the Thread
class and can be called without creating an instance of Thread
. However, it only affects the current thread and does not pause any other threads in the program.