我不能评论你的问题,因为我没有50分,所以我将不得不在这里写一个问题的答案。
您是说上面的代码无法正常工作。什么不工作?什么是症状,你期望发生什么?
其中一个问题是您只重复数秒,完全忽略分钟和小时。另一个是你正在创建一个根本不用的线程。第三个是你在for循环中调用Thread.sleep(1000)
,但我不确定你是否知道它会完全阻塞Thread,直到它完成。
首先,for循环应该开始:
for (int a = hours * 3600 + 60 * minutes + seconds; a >= 0; a--)
其次,Thread thread = new Thread();
完全不使用。
第三,Thread.sleep(1000)
将阻止当前线程,直到它完成。
最后,您的条件是a <= 0
而不是a >= 0
。
所以,你可以调整上述代码的方法之一是:
private void countDownTimer() throws InterruptedException {
int hours = (int) jSpinner1.getValue();
int minutes = (int) jSpinner2.getValue();
int seconds = (int) jSpinner3.getValue();
for (int a = hours * 3600 + 60 * minutes + seconds; a >= 0; a--) {
Thread.sleep(1000);
System.out.println(a);
}
}
}
这是假设的“不工作”意味着它忽略分钟和小时。
另一种解决方案是创建一个回调函数一个新的线程,会被调用一次,倒数计时器达到零:
public class CountDownRunnable implements Runnable {
private final int hours;
private final int minutes;
private final int seconds;
public CountDownRunnable(int hours, int minutes, int seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
public void run() {
for (int a = hours * 3600 + 60 * minutes + seconds; a >= 0; a--) {
Thread.sleep(1000);
System.out.println(a);
}
// Here goes your code that will be invoked once the timer reaches zero...
}
}
然后你的方法应该是这样的:
private void countDownTimer() throws InterruptedException {
(new Thread(new HelloRunnable())).start();
}
谁能帮帮我吗??? –
也许你可以使用https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#scheduleAtFixedRate(java.util.TimerTask,%20long,%20long) –