Java пауза на время
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in 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:
public class SleepMessages < public static void main(String args[]) throws InterruptedException < String importantInfo[] = < "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" >; for (int i = 0; i < importantInfo.length; i++) < //Pause for 4 seconds Thread.sleep(4000); //Print a message System.out.println(importantInfo[i]); >> >
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 .
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 ...