java 长时间倒计时,Java中的重复倒数计时器

I'm trying to implement a countdown timer into a pre-existing public class and I have a few questions.

An overview: I want to have a timer within a program that counts down from 60 (seconds) once the program is initialized.

If the timer reaches zero, the program quits.

If the user meets certain parameters within the 60 second time frame, the timer resets to 60, presents a new set of parameters, and begins the countdown again. It should be able to do this an infinite number of times, until the user fails to meet parameters within 60 seconds.

There will also be some sort of (TBD) GUI representation of the timer, most likely either numerical countdown or JProgressBar.

I'm semi-new (~3 months) to programming, self-taught, and still learning lots (so be gentle) :)

My questions are:

What is the best way to implement this?

I'm assuming this needs to run in a thread?

Will the timer be easily configurable? (not important, just interesting)

Thanks for your help. If you need to see code, I can find some.

EDIT: Just for some clarification/context:

This is for a timed racing video game I'm working on to develop my skills as a programmer. The idea is that a player has 60 seconds to complete a lap. If the player completes a successful lap, the timer resets to 60 seconds and the track changes to be slightly more difficult. The game runs until the player is unable to complete a lap in 60 seconds due to the difficulty. The game records the number of laps as a high score, and asks to player if they would like to try again.

解决方案

If I were you, I'd use:

an AtomicInteger variable which would keep the current countdown value;

a timer thread that would wake up every 1s and decrementAndGet() the variable, comparing the result to zero and terminating the app if the result is zero;

(possibly) a thread that would also wake up every 1s to repaint the GUI -- the best approach here depends on your GUI framework.

Finally, whenever you need to reset the count back to 60s, you just call set(newValue) from any thread.

The timer thread's run() method could be as simple as:

for (;;) {

if (counter.decrementAndGet() <= 0) {

// TODO: exit the app

}

Thread.sleep(1000);

}

I think it's much easier to get this right than trying to manage multiple Timer objects.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值