How to delay for a few seconds in Java
This tutorial explains how to create program delays in Java and gives some sample code to understand it.
There are several ways to create a time delay, such as TimeUnit.sleep()
,, ScheduleAtFixedRate()
etc. Thread.sleep()
Let's look at an example.
Thread.sleep()
Creating delays using methods
in Java
Thread
Is a Java class used to create and execute tasks concurrently, and provides a sleep()
method to pause the current execution for a period of time.
public class SimpleTesting {
public static void main(String[] args) {
try {
for (int i = 0; i < 2; i++) {
Thread.sleep(1000);
System.out.println("Sleep " + i);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Sleep 0
Sleep 1
TimeUnit.sleep()
Delaying
with method in Java
In this example, we use the method TimeUnit
of the class sleep()
to delay the execution for a specified time. TimeUnit
The class belongs to a concurrent API package in Java.
import java.util.concurrent.TimeUnit;
public class SimpleTesting {
public static void main(String[] args) {
try {
for (int i = 0; i < 2; i++) {
TimeUnit.SECONDS.sleep(2);
System.out.println("Sleep " + i);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Sleep 0
Sleep 1
ScheduledExecutorService
Delaying
in Java using
Java provides a class ScheduledExecutorService
to schedule execution in a concurrent environment. We can use its run()
methods to execute separate execution paths. See the following example.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String args[]) {
try {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
executeTask();
}
}, 0, 1, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println(e);
}
}
private static void executeTask() {
System.out.println("Task Executing... ");
}
}
Output:
Task Executing...
Task Executing...
Task Executing...
ScheduledExecutorService
Delaying
in Java using
If you are using Java 9 or higher, you can use the concept of method reference scheduleAtFixedRate()
to call methods from within a method. See the following example.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SimpleTesting {
public static void main(String[] args) {
try {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(SimpleTesting::executeTask, 1, 2, TimeUnit.SECONDS);
} catch (Exception e) {
System.out.println(e);
}
}
private static void executeTask() {
System.out.println("Task Executing... ");
}
}
Output:
Task Executing...
Task Executing...
Task Executing...
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
How to Convert Hashmap to JSON Object in Java
Publish Date:2025/04/14 Views:112 Category:Java
-
This article explains how to convert a Hashmap to a JSON object in Java. We will see a detailed example of creating a hashmap and then converting it to a JSON object. Hashmap and JSON are both very commonly used by developers as they help u
How to sort a Map by value in Java
Publish Date:2025/04/14 Views:170 Category:Java
-
This tutorial explains how to Mapkey, value sort pairs by value in Java and lists some sample codes to understand it. There are several ways to Map sort . Here we use sort() the , sorted() method, and Comparator interface. Let's look at an
How to Print a HashMap in Java
Publish Date:2025/04/14 Views:84 Category:Java
-
This tutorial explains how to print HashMap an element in Java and also provides some sample code to understand the topic. HashMap It is Map an implementation class of the interface and is used to collect elements into key and value pairs.
Updating Hashmap Values in Java
Publish Date:2025/04/14 Views:88 Category:Java
-
This article explains how to use the two methods contained in the HashMap class in Java - update put() and replace() update the values in a HashMap. hashmap.put() Update the value in Hashmap in Java using When we want to HashMap inser
Difference between hashmap and map in Java
Publish Date:2025/04/14 Views:193 Category:Java
-
This tutorial explains the key differences between Map and in Java HashMap . In Java, Map is an interface for storing data in key-value pairs, and HashMap is Map an implementation class of the interface. Java has several classes ( TreeHashM
Get user home directory in Java
Publish Date:2025/04/14 Views:161 Category:Java
-
This tutorial explains how to get the user's home directory in Java and lists some sample code to guide you through the topic. For a multi-user operating system, each user has a file system directory; this directory is called the user's hom
Difference between size and length in Java
Publish Date:2025/04/14 Views:114 Category:Java
-
This tutorial explains the difference between size and length in Java. We have also listed some sample codes to help you understand the topic. Java has a size() method and a length property. Beginners may think that they are interchangeable
Mutex Locks in Java
Publish Date:2025/04/14 Views:198 Category:Java
-
In the field of computer science, mutual exclusion or mutex is known as the property of concurrency control. Every computer uses a minimum sequence of program instructions called a thread. At a time, the computer works on one thread. For be
How to compare characters for equality in Java
Publish Date:2025/04/14 Views:128 Category:Java
-
This tutorial shows you how to check if two characters are equal in Java. In Java, we can use the equals( == ) operator or the Character compare() equals() method of the Character class to compare two characters. If you are working with pri