Search code examples
javatimerpause

How can i make pause option in java


Now I'm using java to create Timer program. But the problem is.. I want to add pause option in my program but i cannot find How to add pause option.. So Please give me some advice on how to insert a pause option..

import java.util.Scanner;
public class HelloWorld {
    public static void main(String[] args) throws InterruptedException {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter Minutes : ");
        int min = sc.nextInt();
        long sec = min * 60;
        for(long i = sec; i >= 0; i--) {
            if(i % 30 == 0) {
                System.out.println(i/60 + " min" + i%60 + " sec");
            }
            Thread.sleep(1000);
        }
        System.out.println("Timer is over..");
    }
}

Solution

  • I'm assuming you want to give the user the option to enter something and cause the countdown to pause. The problem (I think) is that if you ask for input, then that will block the current thread of execution, hence your timer will freeze.

    To solve this, you need some form of asynchronous execution. You might want to take a look at Timer: you can use this to schedule a callback to occur every second. This callback function could print the next number in the countdown sequence, while your main thread waits for user input and cancels the timer if the user types pause.