java 简单的java倒计时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12465127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple java countdown
提问by Johannes Flood
I'm working on a schoolproject in java and get figure out how to create a timer. The timer i'm trying to build is suppose to count down from 60 seconds. Please help me!
我正在用 java 进行一个学校项目,并弄清楚如何创建一个计时器。我正在尝试构建的计时器假设从 60 秒开始倒计时。请帮我!
/Johannes
/约翰内斯
回答by F. Mayoral
You can use:
您可以使用:
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
}
}
Or something like that
或类似的东西
EDIT, i Know this is not the best option, otherwise you should create a new class:
编辑,我知道这不是最好的选择,否则你应该创建一个新类:
Correct way to do this:
执行此操作的正确方法:
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
}
}
}
}
Then you do in your code: Thread thread = new Thread(MyTimer);
然后你在你的代码中做: Thread thread = new Thread(MyTimer);
回答by Piyush Mattoo
Look into Timer, ActionListener, Thread
回答by fthopkins
It is simple to countdown with Java. Lets say you want to countdown 10 min so Try this.
用Java倒计时很简单。假设你想倒计时 10 分钟,所以试试这个。
int second=60,minute=10;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
second--;
// put second and minute where you want, or print..
if (second<0) {
second=59;
minute--; // countdown one minute.
if (minute<0) {
minute=9;
}
}
}
};
new Timer(delay, taskPerformer).start();
回答by BSull
There are many ways to do this. Consider using a sleep function and have it sleep 1 second between each iteration and display the seconds left.
有很多方法可以做到这一点。考虑使用 sleep 函数并让它在每次迭代之间休眠 1 秒并显示剩余的秒数。
回答by Jon7
Since you didn't provide specifics, this would work if you don't need it to be perfectly accurate.
由于您没有提供细节,如果您不需要它完全准确,这将起作用。
for (int seconds=60 ; seconds-- ; seconds >= 0)
{
System.out.println(seconds);
Thread.sleep(1000);
}