Java подождать 5 секунд

How to Add Delay in Java For Few Seconds

In this tutorial, I will be sharing how to add a delay in java for a few seconds. Sometimes we need to introduce a delay in the execution of our java program. It can be achieved in 3 ways.

1. Using Thread.sleep() method
2. Using TimeUnit.XXX.sleep() method
3. Using ScheduledExecutorService

Let’s dive deep into the topic.

Add Delay in Java For Few Seconds

1. Using Thread.sleep() method

The easiest way to delay a java program is by using Thread.sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.
Syntax:

Thread.sleep( time In Milliseconds) 

Note: Unit of time for Thread’s class static sleep method is in milliseconds. So, in order to delay for 7 seconds, we need to pass 7000 as an argument in the sleep method.

public class JavaHungry  public static void main(String args[])  try  System.out.println("Start of delay: "+ new Date()); // Delay for 7 seonds Thread.sleep(7000); System.out.println("End of delay: "+ new Date()); > catch(InterruptedException ex)  ex.printStackTrace(); > > > 

Output:
Start of delay: Tue Oct 13 09:04:52 GMT 2020
End of delay: Tue Oct 13 09:04:59 GMT 2020

2. Using TimeUnit.XXX.sleep() method

There is also another way to add a delay in the Java program i.e by using TimeUnit’s sleep method.

TimeUnit.SECONDS.sleep(time In Seconds) 
TimeUnit.MINUTES.sleep(time In Minutes) 
TimeUnit.MILLISECONDS.sleep(time In Milliseconds) 
import java.util.concurrent.TimeUnit; import java.util.Date; public class JavaHungry  public static void main(String args[])  try  System.out.println("Start of delay: "+ new Date()); // Delay for 7 seonds TimeUnit.SECONDS.sleep(7); System.out.println("End of delay: "+ new Date()); // Delay for 1 minute TimeUnit.MINUTES.sleep(1); // Delay for 5000 Milliseconds TimeUnit.MILLISECONDS.sleep(5000); > catch(InterruptedException ex)  ex.printStackTrace(); > > > 


Output:

Start of delay: Tue Oct 13 09:26:39 GMT 2020
End of delay: Tue Oct 13 09:26:46 GMT 2020

3. Using ScheduledExecutorService

The Executor framework’s ScheduledExecutorService interface can also be used to add a delay in the java program for a few seconds. Among all the methods described in this post, this is the most precise way to add delay. We will use the schedule() method to run the piece of code once after a delay.

import java.util.concurrent.TimeUnit; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService;
public class JavaHungry  public static void main(String args[])  ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); /* schedule(ClassName::anyTask, delayInSeconds, TimeUnit.SECONDS) where anyTask() is the name of the method we want to execute and ClassName is the class containing the anyTask() method */ service.schedule(JavaHungry::executeTask, 5, TimeUnit.SECONDS); > public static void executeTask() System.out.println(" Task is running after 5 seconds"); > > 

Output:
Task is running after 5 seconds

That’s all for today. Please mention in the comments in case you have any questions related to how to add a delay in java for a few seconds.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry

Источник

Java wait seconds or delay Java program for few secs

Delay java program by few seconds

In this post, we will see how to delay java program for few secs or wait for seconds for java program to proceed further.

We need to delay a java programs in many situation where we want to wait for some other task to finish.

There are multiple ways to delay execution of java program or wait for seconds to execute it further.

Using Thread.sleep

Sleep method causes current thread to pause for specific duration of time.We can use Thread’s class sleep static method delay execution of java program.

Here is sample code to the same.

Please note that Unit of time is milliseconds for sleep method, that’s why we have passed 5000 for 5 secs delay.

Sleep method is not always accurate as it depends on system timers and schedulers.

Using TimeUnit.XXX.sleep method

You can use java.util.concurrent.TimeUnit to sleep for specific duration of time.

For example:
To sleep for 5 mins, you can use following code

To sleep for 10 sec, you can use following code

Internally TimeUnit.SECONDS.sleep will call Thread.sleep method. Only difference is readability.

Using ScheduledExecutorService

You can also use ScheduledExecutorService which is part of executor framework. This is most precise and powerful solution to pause any java program.

I would strongly recommend to use ScheduledExecutorService in case you want to run the task every secs or few secs delay.

For example:
To run the task every second, you can use following code.

executorService . scheduleAtFixedRate ( DelayFewSecondsJava : : runTask , 0 , 1 , TimeUnit . SECONDS ) ;

executorService.scheduleAtFixedRate(DelayFewSecondsJava::runTask, 0, 1, TimeUnit.SECONDS);
Here DelayFewSecondsJava is classname and runTask is method name of that class.

Running the task each second
Running the task each second
Running the task each second
Running the task each second

Frequently asked questions on Java wait seconds

How to wait for 5 seconds in java?

You can simply use below code to wait for 5 seconds.

How to wait for 1 seconds in java?

You can simply use below code to wait for 1 seconds.

How to pause for 5 seconds in java?

Pause and wait are synonyms here, so you can simply use below code to pause for 5 seconds.

That’s all how to delay java program for few seconds or how to wait for seconds in java.

Was this post helpful?

You may also like:

Get Thread Id in Java

ArrayBlockingQueue in java

How to print even and odd numbers using threads in java

Why wait(), notify() And notifyAll() methods are in Object Class

Custom BlockingQueue implementation in java

Difference between Runnable and Callable in java

Java Runnable example

Java Executor framework tutorial with example

Java ExecutorCompletionService

Share this

Author

Get Thread Id in Java

Get Thread Id in Java

Table of ContentsGet Thread Id in JavaGet Thread Id of Current Running ThreadGet Thread id of Multiple Threads In this article, we will learn to get thread id of a running thread in Java. An Id is a unique positive number generated at the time of thread creation. This id remains unchanged during the lifetime […]

ArrayBlockingQueue in java

ArrayBlockingQueue in java

Table of ContentsWhat is BlockingQueueArrayBlockingQueueFeaturesConstructorsMethodsUsage ScenariosImplementation CodeSummary In this article, we will understand the Java concurrent queue, BlockingQueue. We will then go deep into it’s one of the implementation, ArrayBlockingQueue. What is BlockingQueue BlockingQueue interface was introduced in Java 5 under concurrent APIs and it represents a thread-safe queue in which elements can be added […]

How to print even and odd numbers using threads in java

Table of ContentsProblemSolution 1Print even and odd numbers using threads in javaSolution 2: Using remainder In this post, we will see how to print even and odd numbers using threads in java. see also: How to print sequence using 3 threads in java Problem You are given two threads. You need to print odd numbers […]

wait(),notify() and notifyAll() in java

Why wait(), notify() And notifyAll() methods are in Object Class

In this post, we will see why wait(), notify() And notifyAll() methods are in Object Class And Not in Thread Class. This is one of the most asked java multithreading interview questions. You might know that wait(), notify() And notifyAll() Methods are in Object class and do you know the reason for the same? Let’s […]

Custom BlockingQueue in java

Custom BlockingQueue implementation in java

In this post, we will see how to create your own custom BlockingQueue. This is one of the most asked java interview questions. You need to implement your own BlockingQueue. This question helps interviewer to get your understanding of multithreading concepts. Here is simple implementation of BlockingQueue. We will use array to store elements in […]

Difference between Runnable and Callable in java

Difference between Runnable and Callable in java

Runnable and Callable interface both are used in the multithreading environment.Callable is available in java.util.concurrent.Callable package and Runnable in java.lang.Thread. Difference between Runnable and Callable interface in java Runnable was introduced in java 1.0 version While Callable is an extended version of Runnable and introduced in java 1.5 to address the limitation of Runnable. Runnable […]

Источник

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.

Источник

Читайте также:  Php respond with 404
Оцените статью