问题
I have a few questions about having code that runs automatically within a given interval. I'm programming a kind of game mode where it checks if the players have killed all the monsters in the map (I have my methods for these). I was wondering what's the best way to program this check? I've looked up ways where a person made a ScheduledExecutorService during a class constructor....
private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
But I saw online where people used
static void main(String[] args) {
And a run method to do the checks. Which would be better? I'm simply wanting to have a check that runs every few or so seconds that sees if the player has cleared the map, and if he or she has, then to progress to the next stage.
回答1:
I think you can check this every time the player kills a monster. Maybe you want to listen to a KillMonster
event. You can create interfaces and implement that in your other class.
public interface KillMonsterEventListener {
void onKillMonster ();
}
And then in the player class you can call a method to call onKillMonster()
of all the event listeners. I think you know how to do that. Just create a list of KillMonsterEventListener
s and have a method like:
public void addKillMonsterEventListener (KillMonsterEventListener listener) {
listeners.add (listener); //listeners is the list of KillMonsterEventListeners.
}
回答2:
Overall, it is somewhat costly to use Executor
for just that, because you can easily have a counter for number of monsters and modify it whenever a monster is killed in the update tick. When it reaches 0, the player has cleared the level. Generally Executor
is fine for larger operations like autosave to the file, it's also worth noting that the code will be executed on a background thread. Since you are just going to query the number of monsters left in the game and not alter UI, it should be fine.
Regards static void main(String[] args) {
I don't see how that fits in the question.
来源:https://stackoverflow.com/questions/31559336/making-code-that-runs-automatically-within-a-given-interval