简单的java倒计时

时间:2012-09-17 18:29:23

标签: java multithreading timer countdown

我正在研究java中的学校项目,并弄清楚如何创建一个计时器。 我正在尝试构建的计时器应该从60秒倒计时。 请帮帮我!

/ Johannes

5 个答案:

答案 0 :(得分:2)

您可以使用:

 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
           }
         }
    }

}

然后你在你的代码中做:     Thread thread = new Thread(MyTimer);

答案 1 :(得分:1)

答案 2 :(得分:0)

有很多方法可以做到这一点。考虑使用睡眠功能,让它在每次迭代之间休眠1秒钟,并显示剩下的秒数。

答案 3 :(得分:0)

由于您没有提供详细信息,如果您不需要它完全准确,这将起作用。

for (int seconds=60 ; seconds-- ; seconds >= 0)
{
    System.out.println(seconds);
    Thread.sleep(1000);
}

答案 4 :(得分:0)

使用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();