Как сделать задержку в java
Перейти к содержимому

Как сделать задержку в java

  • автор:

Pausing Execution with Sleep

Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

The SleepMessages example uses sleep to print messages at four-second intervals:

Notice that main declares that it throws InterruptedException . This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn't bother to catch InterruptedException .

Добавить задержку в Java

В этом посте пойдет речь о том, как добавить в Java задержку на несколько секунд.

1. Использование ScheduledExecutorService

Идея состоит в том, чтобы получить исполнитель, который может планировать выполнение команд после заданной начальной задержки или периодически. Чтобы выполнить задачу один раз после задержки, используйте schedule() метод. Например, следующий код вызывает функцию run() метод после первоначальной задержки в 1 секунду.

How do I make a delay in Java?

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

I want to build a step sequencer.

How do I make a delay in Java?

user's user avatar

8 Answers 8

If you want to pause then use java.util.concurrent.TimeUnit :

To sleep for one second or

To sleep for a minute.

As this is a loop, this presents an inherent problem — drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don’t use sleep .

Further, sleep isn’t very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay .

How to pause the code execution in Java

Sometimes you want to pause the execution of your Java code for a fixed number of milliseconds or seconds until another task is finished. There are multiple ways to achieve this.

Thread.sleep() method

The quickest way to stop the code execution in Java is to instruct the current thread to sleep for a certain amount of time. This is done by calling the Thread.sleep() static method:

The code above stops the execution of the current thread for 2 seconds (or 2,000 milliseconds) using the Thread.sleep() method.

Also, notice the try. catch block to handle InterruptedException . It is used to catch the exception when another thread interrupts the sleeping thread.

This exception handling is necessary for a multi-threaded environment where multiple threads are running in parallel to perform different tasks.

TimeUnit.SECONDS.sleep() method

Please enable JavaScript

For better readability, you can also use the TimeUnit.SECONDS.sleep() method to pause a Java program for a specific number of seconds as shown below:

Under the hood, the TimeUnit.SECONDS.sleep() method also calls the Thread.sleep() method. The only difference is readability that makes the code easier to understand for unclear durations.

The TimeUnit is not just limited to seconds. It also provides methods for other time units such as nanoseconds, microseconds, milliseconds, minutes, hours, and days:

ScheduledExecutorService interface

The sleep times are inaccurate with Thread.sleep() when you use smaller time increments like nanoseconds, microseconds, or milliseconds. This is especially true when used inside a loop.

For every iteration of the loop, the sleep time will drift slightly due to other code execution and become completely imprecise after some iterations.

For more robust and precise code execution delays, you should use the ScheduledExecutorService interface instead. This interface can schedule commands to run after a given delay or at a fixed time interval.

For example, to run the timer() method after a fixed delay, you use the schedule() method:

Similarly, to call the method timer() every second, you should use the scheduleAtFixedRate() method as shown below:

Here is a an example output of the above code:

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *