如何在输出屏幕中显示定时器的秒数?

时间:2016-04-17 16:07:34

标签: java

import java.awt.Toolkit;
import java.util.Timer;
import java.util.TimerTask;

public class Java {
  Toolkit toolkit;
  Timer timer;
int t=10000,total;
  public Java(int seconds) {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    total =seconds * t;
    System.out.println(total);
    timer.schedule(new RemindTask(), total); 
  }

  class RemindTask extends TimerTask {
    public void run() {        
      System.out.println("Time's up!");
      toolkit.beep();
      System.exit(0);
    }
  }

  public static void main(String args[]) {
    new Java(5);
    System.out.println("Timer started");
  }
}

如何在输出屏幕中显示类似于倒数计时器的秒数,我想在测验程序中使用它

0:53 => 0:52 喜欢这个 ......

1 个答案:

答案 0 :(得分:0)

您可以使用Timer.scheduleAtFixedRate的句点以固定费率(1 second)安排任务。我们应尽可能避免调用System.exit(0)并等待线程完成其任务。我们可以使主线程(启动计时器的线程)在计时器任务的持续时间内休眠,然后当它最终唤醒时,它会取消计时器:

private final Timer timer;
public CountDownTimer(int seconds) {
    timer = new Timer();
    timer.scheduleAtFixedRate(new RemindTask(seconds), 0, 1000);
}

class RemindTask extends TimerTask {
    private volatile int remainingTimeInSeconds;
    public RemindTask(int remainingTimeInSeconds) {
        this.remainingTimeInSeconds = remainingTimeInSeconds;
    }

    public void run() {
        if (remainingTimeInSeconds != 0) {
            System.out.println(remainingTimeInSeconds + " ...");
            remainingTimeInSeconds -= 1;
        }
    }
}

public static void main(String args[]) throws InterruptedException {
    CountDownTimer t = new CountDownTimer(5);
    System.out.println("Timer started");
    Thread.sleep(5000);
    t.end();
}

private void end() {
    this.timer.cancel();
}