What is the most efficient way to run many things from different time intervals in Java 6

I am working on a scroller GUI in Java. I have many kinds of enemies whose AIs run away with Swing timers. As far as I understand, Swing timers are resource intensive, but I still want my enemies to move at different intervals. Is there a better way to manage things than using a different Swing timer for each kind of enemy?

+6
source share
2 answers

The best way to solve this problem is to keep a list of enemies that exist on the screen, every time you make the next screen, your main rendering cycle should determine the weather, it should call any of the methods of the Enemy object or not.

public interface Enemy { public void doNextThing(); } public class TimedEnemy implements Enemy { private long lastExecute; private Enemy enemy; private long threshHold; public TimedEnemy(Enemy enemy, long threshold) { this.lastExecute = System.currentTimeMills(); this.enemy = enemy; this.threshold = threshold; } public void doNextThing() { long duration = System.currentTimeMills() - lastExecute; if( duration >= threshold) { lastExecute = System.currentTimeMills(); this.enemy.doNextThing(); } } } // main Render Loop List<Enemy> enemies = new ArrayList<Enemy>(); TimedEnemy easy = new TimedEnemy(new EasyEnemy(),1000); TimedEnemy hard = new TimeEnemy(new HardBadGuyEnemy(),100); TimedEnemy boss = new TimeEnemy(new VeryBadBossEnemy(),50); enemies.add(easy); enemies.add(hard); enemies.add(boss); for( Enemy enemy : enemies) { enemy.doNextThing(): } 

If you really need each enemy AI to start in its own thread, you need to use the TaskExecutor functions for Java 5 with the concept of Futures. Although running each AI on separate threads means you have to be careful with thread synchronization.

+4
source

Source: https://habr.com/ru/post/908683/


All Articles