Home >Java >javaTutorial >How Can I Create a Delay in Java?

How Can I Create a Delay in Java?

DDD
DDDOriginal
2024-12-10 15:20:12617browse

How Can I Create a Delay in Java?

Creating a Delay in Java

In Java, sometimes it's necessary to pause execution for a specified duration. This task can be accomplished using several methods.

One common approach is to utilize the java.util.concurrent.TimeUnit class, which provides methods for delaying execution for periods of time. To pause for one second, you can use:

TimeUnit.SECONDS.sleep(1);

Alternatively, you can specify a different time unit:

TimeUnit.MINUTES.sleep(1);

However, it's important to note that using sleep() can introduce drift over time, as it's based on system time, which can vary.

For greater flexibility and control, consider using a ScheduledExecutorService. Specifically, the scheduleAtFixedRate() method can be utilized to run a task at regular intervals:

ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);

This method will execute the myTask() method every second, starting immediately.

The above is the detailed content of How Can I Create a Delay in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn