开发者

Java Timer Reusage

开发者 https://www.devze.com 2023-01-13 16:22 出处:网络
I\'m currently trying to get a small brick-breaker game I made to effectively use some form of power-ups or bonuses. I have have it mostly implemented right now. However I have a problem. I use java.u

I'm currently trying to get a small brick-breaker game I made to effectively use some form of power-ups or bonuses. I have have it mostly implemented right now. However I have a problem. I use java.util.Timer to determine how long the power-up lasts. Most likely, that power-up is going to be chosen (by a random number generator) more than once. However, a Java Timer can only be used once, and after it's cancel() method is called, it's done. Right now, I set up the game to mark a power-up as used and to never use it again. Is there a way to get around this? Here's the method that is called when the LongPaddle power-up is chosen:

public void longPaddleTime(int seconds) { //longPaddle Timer Method - gets called when the longPaddle bonus is enabled; shuts off longPaddle after a set amount of time
    timerLP.schedule(new TaskLP(), seconds*1000);

}
class TaskLP extends TimerTask { //The task to be run after the timer in longPaddleTime runs out  
    public void run() {
        longPaddle=false; //Disable LongPaddle
        bonusActive=false;
        LPused=true; //Mark as used
        timerLP.cancel()开发者_如何学C; //Terminate the timer thread
        timerLP.purge();
    }
}


You don't need to cancel() your timer - Timer.schedule(TimerTask, long delay) will only run the specified task once. You only need to cancel() a timer if you want to terminate everything it's doing.

For your case (scheduling a task once), there's no cleanup required in the Timer class. If you had a repeating task and you wanted to stop just that one task, you could call TimerTask.cancel() to prevent it from reoccuring, while still allowing the Timer to be reused for other purposes.


You don't have to cancel the timer in your TaskLP.

Create a Timer object that lives in Application scope and just schedule new TimerTasks as need arises.

BTW, although not officially deprecated, Timer functionality has been superseeded by ScheduledExecutorService. I suggest, if you start from scratch to use this framework.

Executors utility class has a few methods that simplify the construction of the ScheduledExecutorService.

0

精彩评论

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

关注公众号