Java - 没有GUI的倒数计时器

Kyl*_*e93 6 java countdown

基本上我正在制作一个基于文本的"游戏"(不是一个游戏,更多的是一种提高基本java技能和逻辑的方法).但是,作为其中的一部分,我希望有一个计时器.它会减少我希望从变量到0的时间.现在,我已经看到了一些使用gui执行此操作的方法,但是,有没有一种方法可以在没有gui/jframe等的情况下执行此操作.

所以,我想知道的是.你可以在不使用gui/jframe的情况下从x到0进行倒计时.如果是这样,你会怎么做?

谢谢,一旦我有一些想法将编辑进展.

编辑

// Start timer
Runnable r = new TimerEg(gameLength);
new Thread(r).start();
Run Code Online (Sandbox Code Playgroud)

以上是我如何调用线程/计时器

public static void main(int count) {
Run Code Online (Sandbox Code Playgroud)

如果我在TimerEg类中有这个,那么计时器符合.但是,当我在另一个线程中编译main时.

错误

现在,我完全错过了解线程以及这将如何工作?还是有什么我想念的?

错误:

constructor TimerEg in class TimerEg cannot be applied to given types;
required: no arguments; found int; reason: actual and formal arguments differ in length
Run Code Online (Sandbox Code Playgroud)

在线发现 Runnable r = new TimerEg(gameLength);

Hov*_*els 9

与GUI相同,您使用的是Timer,但是在这里使用的是java.util.Timer,而不是使用Swing Timer.有关详细信息,请查看Timer API.还可以查看TimerTask API,因为您可以将它与Timer结合使用.

例如:

import java.util.Timer;
import java.util.TimerTask;

public class TimerEg {
   private static TimerTask myTask = null;
   public static void main(String[] args) {
      Timer timer = new Timer("My Timer", false);
      int count = 10;
      myTask = new MyTimerTask(count, new Runnable() {
         public void run() {
            System.exit(0);
         }
      });

      long delay = 1000L;
      timer.scheduleAtFixedRate(myTask, delay, delay);
   }
}

class MyTimerTask extends TimerTask {
   private int count;
   private Runnable doWhenDone;

   public MyTimerTask(int count, Runnable doWhenDone) {
      this.count = count;
      this.doWhenDone = doWhenDone;
   }

   @Override
   public void run() {
      count--;
      System.out.println("Count is: " + count);
      if (count == 0) {
         cancel();
         doWhenDone.run();
      }
   }

}
Run Code Online (Sandbox Code Playgroud)


Cur*_*ous 5

您可以编写自己的倒数计时器,如下所示:

public class CountDown {
    //Counts down from x to 0 in approximately
    //(little more than) s * x seconds. 
    static void countDown(int x, int s) {
        while (x > 0 ) { 
            System.out.println("x = " + x); 
            try {
                Thread.sleep(s*1000);
            } catch (Exception e) {}
            x--;
        }   
    }

    public static void main(String[] args) {
        countDown(5, 1); 
    }   
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用Java Timer API