Java 中的循环倒数计时器 [英] Recurring Countdown Timer in Java

查看:37
本文介绍了Java 中的循环倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在预先存在的公共课程中实现倒数计时器,但我有几个问题.

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

概述:我想在程序中设置一个计时器,在程序初始化后从 60(秒)开始倒计时.

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.

如果用户在 60 秒的时间范围内满足某些参数,计时器将重置为 60,显示一组新参数,并再次开始倒计时.它应该可以无限次执行此操作,直到用户在 60 秒内未能满足参数.

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.

还会有某种(待定)计时器的 GUI 表示形式,最有可能是数字倒计时或 JProgressBar.

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

我是半新手(约 3 个月)编程,自学,还在学习很多(所以要温柔):)

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

我的问题是:

  1. 实现此目的的最佳方法是什么?

  1. 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.

只是为了一些澄清/上下文:这是一款计时赛车视频游戏,我正在努力开发我作为程序员的技能.这个想法是玩家有 60 秒的时间来完成一圈.如果玩家成功完成一圈,计时器将重置为 60 秒,并且赛道会变得稍微困难​​一些.游戏一直运行到玩家因难度无法在 60 秒内完成一圈.游戏将圈数记录为高分,并询问玩家是否愿意再试一次.

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.

推荐答案

如果我是你,我会用:

  1. an AtomicInteger 保持当前倒计时值的变量;
  2. 每 1 秒唤醒一次的定时器线程和 decrementAndGet() 变量,将结果与零进行比较,如果结果为零则终止应用程序;
  3. (可能)一个每 1 秒唤醒一次以重新绘制 GUI 的线程——此处的最佳方法取决于您的 GUI 框架.

最后,每当您需要将计数重置为 60 秒时,您只需调用 set(newValue) 来自任何线程.

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

定时器线程的 run() 方法可以很简单:

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

for (;;) {
  if (counter.decrementAndGet() <= 0) {
    // TODO: exit the app
  }
  Thread.sleep(1000);
}

我认为这比尝试管理多个 Timer 对象要容易得多.

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

这篇关于Java 中的循环倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆