Как поставить задержку в java

Метод thread sleep в Java – задержка по времени

Метод Thread.sleep() можно использовать для приостановки выполнения текущего потока на указанное время в миллисекундах. Значение аргумента в миллисекундах не может быть отрицательным, иначе оно выдает исключение IllegalArgumentException.

Существует еще один метод sleep(long millis, int nanos), который можно использовать для приостановки выполнения текущего потока на указанные миллисекунды и наносекунды. Допустимое значение nano second составляет от 0 до 999999.

InterruptedException возникает, если какой-либо поток прервал текущий поток. Прерванное состояние текущего потока очищается при возникновении этого исключения.

public static void sleep(long millis) throws InterruptedException

Как работает Thread Sleep?

Thread.sleep() взаимодействует с планировщиком потока, чтобы перевести текущий поток в состояние ожидания в течение указанного периода времени. По истечении времени, ожидания состояние потока изменяется на работоспособное состояние и ожидает ЦП для дальнейшего выполнения.

Таким образом, фактическое время ожидания текущего потока зависит от планировщика потока, который является частью операционной системы.

Пример thread sleep на Java

Вот простая программа на Java, в которой Thread.sleep() используется для задержки по времени основного потока на 2 секунды.

package com.journaldev.threads; public class ThreadSleep < public static void main(String[] args) throws InterruptedException < long start = System.currentTimeMillis(); Thread.sleep(2000); System.out.println("Sleep time in ms EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="eclipse">package com.tutorial; import java.lang.*; public class ThreadDemo implements Runnable < Thread t; public void run() < for (int i = 10; i < 13; i++) < System.out.println(Thread.currentThread().getName() + " " + i); try < // в течение 1000 миллисекунд Thread.sleep(1000); >catch (Exception e) < System.out.println(e); >> > public static void main(String[] args) throws Exception < Thread t = new Thread(new ThreadDemo()); // this will call run() function t.start(); Thread t2 = new Thread(new ThreadDemo()); // this will call run() function t2.start(); >>

Давайте скомпилируем и запустим программу, это даст следующий результат:
Thread-0 10
Thread-1 10
Thread-0 11
Thread-1 11
Thread-0 12
Thread-1 12

Читайте также:  Php получить mac адрес клиента

Средняя оценка 4.1 / 5. Количество голосов: 10

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Видим, что вы не нашли ответ на свой вопрос.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Источник

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.

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:

try  System.out.printf("Start Time: %s\n", LocalTime.now()); Thread.sleep(2 * 1000); // Wait for 2 seconds System.out.printf("End Time: %s\n", LocalTime.now()); > catch (InterruptedException e)  e.printStackTrace(); > 

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.

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:

try  System.out.printf("Start Time: %s\n", LocalTime.now()); TimeUnit.SECONDS.sleep(2); // Wait 2 seconds System.out.printf("End Time: %s\n", LocalTime.now()); > catch (InterruptedException e)  e.printStackTrace(); > 

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:

// Wait 500 nanoseconds TimeUnit.NANOSECONDS.sleep(500); // Wait 5000 microseconds TimeUnit.MICROSECONDS.sleep(5000); // Wait 500 milliseconds TimeUnit.MILLISECONDS.sleep(500); // Wait 5 minutes TimeUnit.MINUTES.sleep(5); // Wait 2 hours TimeUnit.HOURS.sleep(2); // Wait 1 day TimeUnit.DAYS.sleep(1); 

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:

public class Runner  public static void main(String[] args)  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // Execute timer after 2 seconds service.schedule(Runner::timer, 2, TimeUnit.SECONDS); > public static void timer()  System.out.println("Current time: " + LocalTime.now()); > > 

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

public class Runner  public static void main(String[] args)  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // Execute timer every second service.scheduleAtFixedRate(Runner::timer, 0, 1, TimeUnit.SECONDS); > public static void timer()  System.out.println("Current time: " + LocalTime.now()); > > 
Current time: 08:48:11.350034 Current time: 08:48:12.335319 Current time: 08:48:13.337250 Current time: 08:48:14.334107 Current time: 08:48:15.338532 Current time: 08:48:16.336175 ... 

You might also like.

Источник

Java Delay – 4 Ways to Add Delay in Java

Let’s discuss about scenario when we want to introduce a delay in execution of a subsequent program. Before we move on further to understand the working of delay in Java, let’s understand some practical scenario in which we would need a delay in execution.

As soon as the application is loaded and the user logged in, we want to fetch the current location of the user. We are aware that calling certain API like Google Maps API would take at least 5-8 seconds of time for fetching a response. In such cases we have to use delay in our code.

Delay in Java

Like any other programming language, Java supports delays. To understand the concept of delay we need to understand about Threads in Java, if you are aware about it you can continue reading otherwise we suggest you learn about threads once before moving ahead. Having knowledge of threads you would be for sure aware about main Thread, the thread in which main function is called. So now if we want to use delay the only possible way is pause the execution of Threads. The Java’s API provides methods for this functionality.

The Most Basic Approach: Thread’s class Sleep() Method

As the name suggests, sleep method is a quick but a dirty approach to execute the delay in Java. This method is present in the Thread class. It simply directs the current thread to sleep for a specific time.

The sleep method accepts the input in milliseconds. So, if you want to pause the execution for 5 seconds, you would need to pass 5000 in the sleep method. In case of sleep method the process is shown as work in progress whereas the operation is set to hold. Now, in such scenario the execution of sleep method might be interrupted if the processor needs to work on some other process of high priority. So, for this purpose Java’s API has implemented sleep method to throw InterruptedException.

Below is the implementation of the sleep method of Thread Class.

So, whenever we are calling the sleep method we would need to either forward the exception or handle the exception using try & catch block like shown in the code below:

Sleep with a Unit Time: Time Unit’s sleep() Method

Another way of doing or calling the sleep method is using TimeUnit’s sleep method. Internally it also uses the Thread’s sleep method but it differs in a way that it accepts Unit Time and the same can be passed in arguments, like shown in below:

For java assignment help you can checkout AssignmentCore whose experts will do Java homework for you.

Just Another Delay Approach: wait() Method

We can use the wait method to pause the execution in a multi-threaded environment and inside a synchronized block. We will keep it for discussion later when we discuss thread. So we use wait when we want a particular thread to wait for the execution till informed.

Like wait(), we have a method notify() and notifyAll(), these methods are called after wait() method. We need to make sure that we call the wait() method only from the synchronized block.

Let’s see using a simple example, in the below example we are calculating the sum of first 100 numbers using threads and printing the sum in different thread.

So, below is our ThreadOne class:

And below is the main class which makes the object of ThreadOne and calculates the sum:

The output of the above code would be something like below:

Value of the ThreadOne’s num is: 0

Value of the ThreadOne’s num is: 10 or something, depending on the value at the time the variable sum is sent to console for printing.

We use the same ThreadOne class:

But modify the ThreadMain class as below:

Waiting For the Thread t1 to complete its execution:

Value of the ThreadOne’s num is: 4950

It happened due to wait() which paused the main() thread till the t1 thread executed it’s method and called the notify() method.

Now all out above solutions are either pausing the execution for a specified amount of time, but what about cases when we are ourselves unsure of the exact wait time. For Ex: we are calling an API whose result might be delayed, in such cases above approach would fail to give proper response. To solve this problem Java gave a great solution in terms of Scheduler.

Last but Least: The ExecutorService based Scheduler

ScheduledExecutorService is an interface provided by Java as a precise solution to the delay problem. ExecutorService is interface provided by Java which can schedule the commands to run after a given delay, it also can schedule a task or command to be executed periodically.

Using the interface user can schedule a piece of code at a specific internal or after a specific delay.

To call the scheduled method we simply need to obtain the object of the scheduler service from the Executor. Let’s see using a simple problem statement to understand the brief working of the executor service.

In the example below we are taking an executor service to create a pool of 6 threads and out of these 6 threads we are submitting 2 tasks. Please note the difference between task and thread here. A callable and runnable are the task which may or may not return something, that we will see when we cover ExecutorService in detail.

Источник

Оцените статью