java delay

www‮tual.‬turi.com
java delay

In Java, you can delay the execution of a piece of code by using the Thread.sleep method from the java.lang.Thread class. The sleep method causes the current thread to suspend its execution for a specified number of milliseconds.

Here is an example of how to use the sleep method to delay the execution of a piece of code in Java:

public class Main {
  public static void main(String[] args) throws InterruptedException {
    // Print a message
    System.out.println("Start");

    // Delay the execution for 2 seconds (2000 milliseconds)
    Thread.sleep(2000);

    // Print another message
    System.out.println("End");
  }
}

This code prints the message "Start", then delays the execution for 2 seconds (2000 milliseconds), and finally prints the message "End". When you run this code, the messages will be printed with a 2-second delay between them.

Note that the sleep method throws a InterruptedException, which you must handle or declare in your code. You can handle the exception by using a try-catch block, or you can declare the exception by adding the throws InterruptedException clause to the method signature.

You can also use the java.util.concurrent.TimeUnit class to specify the delay in terms of other time units, such as seconds, minutes, or hours. For example:

import java.util.concurrent.TimeUnit;

public class Main {
  public static void main(String[] args) throws InterruptedException {
    // Print a message
    System.out.println("Start");

    // Delay the execution for 2 minutes (120 seconds)
    TimeUnit.SECONDS.sleep(120);

    // Print another message
    System.out.println("End");
  }
}

This code delays the execution for 2 minutes (120 seconds), using the TimeUnit.SECONDS constant to specify the time unit.

Keep in mind that the sleep method is a blocking operation, which means that it will pause the execution of the current thread until the specified time has elapsed. If you want to delay the execution of a piece of code without blocking the current thread, you can use a timer or a scheduler.

Created Time:2017-11-03 00:14:53  Author:lautturi