How do I make a delay in Java?
To make a delay in Java, you can use the Thread.sleep
method which will pause the current thread for a specified number of milliseconds. Here's an example:
try {
Thread.sleep(1000); // delay for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
Note that the Thread.sleep
method can throw an InterruptedException
, so it's a good idea to include a try-catch block to handle this exception.
Alternatively, you can use the java.util.concurrent.TimeUnit
class to specify the delay time in a more readable format, like this:
try {
TimeUnit.SECONDS.sleep(1); // delay for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
This can be useful if you want to specify the delay time in terms of minutes, hours, or days, rather than in milliseconds.