用Java实现创建类TimerAlarm,让它继承Thread并实现一个秒表的功能,不要使用内置的Timer类,程序运行的结果应该如下图所示:先按照时:分:秒打印时间,然后换一行打印总的秒数。
时间: 2023-06-25 14:03:07 浏览: 87
以下是一个简单的实现代码示例:
```java
public class TimerAlarm extends Thread {
private int hour, minute, second;
private int totalSeconds;
public TimerAlarm(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
this.totalSeconds = hour * 3600 + minute * 60 + second;
}
@Override
public void run() {
while (totalSeconds >= 0) {
System.out.printf("%02d:%02d:%02d\n", hour, minute, second);
System.out.println("Total seconds: " + totalSeconds);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
totalSeconds--;
second--;
if (second < 0) {
minute--;
second = 59;
}
if (minute < 0) {
hour--;
minute = 59;
}
}
System.out.println("Time's up!");
}
public static void main(String[] args) {
TimerAlarm timerAlarm = new TimerAlarm(0, 0, 10);
timerAlarm.start();
}
}
```
在上述代码中,我们将时、分、秒分别存储在 `hour`、`minute` 和 `second` 中,并且将总共的秒数存储在 `totalSeconds` 中。在 `run` 方法中,我们使用一个循环来不断打印当前的时间和总秒数,并且使用 `Thread.sleep(1000)` 来让程序睡眠 1 秒钟。每次循环,我们将 `totalSeconds` 减 1,同时更新 `hour`、`minute` 和 `second` 的值。当 `totalSeconds` 小于 0 时,循环结束,打印 "Time's up!"。在 `main` 方法中,我们创建一个 `TimerAlarm` 对象,并启动它。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)