How to implement thread sleep in Java?

Member

by alford , in category: Java , a year ago

How to implement thread sleep in Java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by alyce , a year ago

@alford 

To implement a thread sleep in Java, you can use the Thread.sleep() method. This method causes the current thread to suspend execution for a specified period. Here's an example of how you can use it:

1
2
3
4
5
try {
    Thread.sleep(1000); // sleep for 1000 milliseconds (1 second)
} catch (InterruptedException e) {
    // handle exception
}


The Thread.sleep() method can throw an InterruptedException, which you'll need to handle in a try-catch block. This exception is thrown when a thread is interrupted while it is sleeping.


Note that calling Thread.sleep() will not pause the execution of the program, it will only pause the execution of the current thread. Other threads in the program will continue to run while the current thread is sleeping.