java中如何设计时间倒计时_java倒计时时间
时间: 2024-05-12 14:13:19 浏览: 168
倒计时_javaSwing_win32.rar
在Java中设计时间倒计时可以使用定时器(Timer)和计时器(CountdownTimer)两种方式。
使用Timer实现倒计时:
```java
import java.util.Timer;
import java.util.TimerTask;
public class CountDownTimer {
static int interval;
static Timer timer;
public static void main(String[] args) {
int delay = 1000;
int period = 1000;
timer = new Timer();
interval = 10;
System.out.println(interval);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println(setInterval());
}
}, delay, period);
}
private static final int setInterval() {
if (interval == 1)
timer.cancel();
return --interval;
}
}
```
使用CountdownTimer实现倒计时:
```java
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownTimer {
public static void main(String[] args) throws InterruptedException {
int duration = 10; // duration in seconds
final CountDownLatch latch = new CountDownLatch(duration);
for (int i = 0; i < duration; i++) {
new Thread() {
public void run() {
try {
latch.countDown();
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
latch.await();
System.out.println("Time's up!");
}
}
```
这两种方式都可以实现倒计时,具体选择哪一种取决于你的需求。
阅读全文