java

How to pause a Java program for X seconds

In this tutorial, we are going to see how to pause a Java program for X seconds. In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to pause a program for a few seconds.
 

Pause a Java program using Thread.sleep():
public class Main {

    public static void main(String[] args) {

        try {
            System.out.println("Task 1...");
            // pause for 10 seconds
            Thread.sleep(10000);
            System.out.println("Task 2...");

        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
    }
}

Output:

Task 1...
(wait 10 seconds)
Task 2...
 

Pause a Java program using TimeUnit:
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {
		
        try {
            System.out.println("Task 1...");
            // pause for 10 seconds
            TimeUnit.SECONDS.sleep(10);
            System.out.println("Task 2...");
			
        } catch (InterruptedException e) {
            e.printStackTrace(); 
        }
    }
}

Output:

Task 1...
(wait 10 seconds)
Task 2...
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *