开发者

Decrement at Regular Intervals in Java

开发者 https://www.devze.com 2022-12-13 23:53 出处:网络
I\'m writing an application开发者_StackOverflow in Java, but need to know how to subtract from a variable once every second. What\'s the easiest way to do this? Thanks!The name of the very Java class

I'm writing an application开发者_StackOverflow in Java, but need to know how to subtract from a variable once every second. What's the easiest way to do this? Thanks!


The name of the very Java class you need to use to do repeating operations is already sitting there in one of your tags! ;)


While the Timer class will work, I recommend using a ScheduledExecutorService instead.

While their usage is extremely similar, ScheduledExecutorService is newer, more likely to receive ongoing maintenance, fits in nicely with other concurrent utilities, and might offer better performance.


class YourTimer extends TimerTask
{
  public volatile int sharedVar = INITIAL_VALUE;

  public void run()
  {
    --sharedVar;
  }

  public static void main(String[] args)
  {
     Timer timer = new Timer();

     timer.schedule(new YourTimer(), 0, 1000);
     // second parameter is initial delay, third is period of execution in msec
  }
}

Remeber that Timer class is not guaranteed to be real-time (as almost everything in Java..)


What are you trying to achieve? I would not try relying on the timer to properly fire exactly once per second. I would simply record the start time, and whenever a timer fires, recalculate what the value of the variable should be. Here's how I would do it...

class CountdownValue {
  private long startTime;
  private int startVal;

  public CountdownValue(int startVal)
  {
     startTime = System.currentTimeMillis();
  }

  public int getValue()
  {
     return startVal - (int)((System.currentTimeMillis() - startTime)/1000);
  }
}


Use a java.util.Timer to create a TimerTask.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号