System pause in java

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.

Источник

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 .

Источник

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 […]

Источник

Thread.sleep() in Java — Java Thread sleep

Thread.sleep() in Java - Java Thread sleep

The Java Thread.sleep() method can be used to pause the execution of the current thread for a specified time in milliseconds. The argument value for milliseconds cannot be negative. Otherwise, it throws IllegalArgumentException .

sleep(long millis, int nanos) is another method that can be used to pause the execution of the current thread for a specified number of milliseconds and nanoseconds. The allowed nanosecond values are between 0 and 999999 .

In this article, you will learn about Java’s Thread.sleep() .

How Thread.sleep Works

Thread.sleep() interacts with the thread scheduler to put the current thread in a wait state for a specified period of time. Once the wait time is over, the thread state is changed to a runnable state and waits for the CPU for further execution. The actual time that the current thread sleeps depends on the thread scheduler that is part of the operating system.

Java Thread.sleep important points

  1. It always pauses the current thread execution.
  2. The actual time the thread sleeps before waking up and starting execution depends on system timers and schedulers. For a quiet system, the actual time for sleep is near to the specified sleep time, but for a busy system, it will be a little bit longer.
  3. Thread.sleep() doesn’t lose any monitors or lock the current thread it has acquired.
  4. Any other thread can interrupt the current thread in sleep, and in such cases InterruptedException is thrown.

Java Thread.sleep Example

Here is an example program where Thread.sleep() is used to pause the main thread execution for 2 seconds (2000 milliseconds):

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 = " + (System.currentTimeMillis() - start)); > > 

First, this code stores the current system time in milliseconds. Then it sleeps for 2000 milliseconds. Finally, this code prints out the new current system time minus the previous current system time:

Output
Sleep time in ms = 2005

Notice that this difference is not precisely 2000 milliseconds. This is due to how Thread.sleep() works and the operating system-specific implementation of the thread scheduler.

Conclusion

In this article, you learned about Java’s Thread.sleep() .

Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Читайте также:  Типы хранения данных java
Оцените статью