Java, replacement for infinite loops?

前端 未结 9 725
花落未央
花落未央 2021-01-13 00:45

I am making a program that shows cellular growth through an array. I have gotten it so when I press the start button, the array updates every 10 seconds in a while(true){} l

9条回答
  •  离开以前
    2021-01-13 01:31

    I personally prefer using the Timer class rather than Thread or Thread.sleep(). The timer class handles both running the code periodically and canceling it.

    Your code would look like:

    TimerTask myTask = new TimerTask() {
      public void run() {
        // here goes my code
      }
    };
    
    Timer timer = new Timer();
    timer.schedule(myTask, 0 /*starts now*/, 10 * 1000 /* every 10 seconds */);
    
    // whenever you need to cancel it:
    timer.cancel();
    

提交回复
热议问题