我正在用 Java 做一个学校项目,需要弄清楚如何创建一个计时器。
我正在尝试构建的计时器应该从 60 秒开始倒计时。
最佳答案
您可以使用:
int i = 60;
while (i>0){
System.out.println("Remaining: "i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
或者类似的东西
编辑,我知道这不是最好的选择,否则你应该创建一个新类:
执行此操作的正确方法:
public class MyTimer implements java.lang.Runnable{
@Override
public void run() {
this.runTimer();
}
public void runTimer(){
int i = 60;
while (i>0){
System.out.println("Remaining: "+i+" seconds");
try {
i--;
Thread.sleep(1000L); // 1000L = 1000ms = 1 second
}
catch (InterruptedException e) {
//I don't think you need to do anything for your particular problem
}
}
}
}
然后你在你的代码中做:
线程线程=新线程(MyTimer);
关于java - 简单的 Java 倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465127/