Java Countdown Timer: Implementation Guide
In Java, a countdown timer can be implemented using java.util.Timer and java.util.TimerTask.
Here is a simple example:
import java.util.Timer;
import java.util.TimerTask;
public class CountdownTimer {
private int seconds;
public CountdownTimer(int seconds) {
this.seconds = seconds;
}
public void start() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
if (seconds > 0) {
System.out.println(seconds);
seconds--;
} else {
System.out.println("倒计时结束");
timer.cancel();
}
}
};
timer.scheduleAtFixedRate(task, 0, 1000); // 每隔1秒执行一次任务
}
public static void main(String[] args) {
CountdownTimer timer = new CountdownTimer(10); // 设置倒计时时间为10秒
timer.start();
}
}
In the code above, a CountdownTimer class is first created to represent a countdown timer, which has a seconds member variable to store the number of seconds in the countdown. The start() method creates a Timer object and uses an anonymous inner class TimerTask to define the task to be executed each time the countdown occurs. In the run() method of the task, it checks if the countdown is greater than 0, if so, it prints the current number of seconds in the countdown and decrements the seconds by 1, otherwise it prints “Countdown End” and cancels the timer. Finally, in the main() method, a CountdownTimer object is created and the start() method is called to begin the countdown.
The countdown timer will execute the task every 1 second, displaying the current countdown seconds until the countdown is finished.