Recurring Countdown Timer in Java

前端 未结 4 1069
自闭症患者
自闭症患者 2021-01-21 21:49

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

4条回答
  •  庸人自扰
    2021-01-21 22:03

    If I were you, I'd use:

    1. an AtomicInteger variable which would keep the current countdown value;
    2. 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;
    3. (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.

提交回复
热议问题