To stop the timer when it reaches zero, we create a condition to check the countdownStarter value. Now inside the run() method, we print countdownStarter, and decrease its value by one. In Runnable, we create a variable countdownStarter and initialize it with the number in seconds from where we want to start the countdown timer. A Runnable instance is used to execute the thread. Next, we override the run() method from the Runnable interface. The Executors.newScheduledThreadPool() function returns a ScheduledExecutorService object that we named scheduler. In this case, we want only one thread to run the timer. In the newScheduledThreadPool() method, we pass the number of threads that we want in the pool. In this first method, we use the ExecutorService interface to call its method newScheduledThreadPool(), which creates a thread pool that uses the same fixed number of assigned threads. Check out the codes we have below! Countdown Timer in Java Using ScheduledExecutorService We can either use the timer in a GUI window or the console just to test it.
Today, we’ll demonstrate how you can make a countdown timer in Java using two methods without relying on any third-party library.
Countdown Timer in Java Using ScheduledExecutorService.