Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

I am working on a side scroller GUI game in Java. I have many kinds of enemies whose AIs run off Swing timers. As I understand it, Swing timers are kind of resource intensive, yet I still want my enemies to move around at different intervals. Is there a more efficient way to run things than using a different Swing timer for each kind of enemy?

like image 338
alexpyoung Avatar asked Feb 17 '12 07:02

alexpyoung


People also ask

What multithreading in how many ways Java implements multithreading explain at least one of these ways with appropriate example?

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.


1 Answers

A better way to solve this problems is to keep a list of enemies that exist on the screen, every time you render the next screen your main render loop should decided weather it should call any of the methods on 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 to have every enemy AI run on its own thread then you need to use a TaskExecutor features of Java 5, with the Futures concept. Although running each AI on separate threads means that you have to be careful with thread synchronization.

like image 104
ams Avatar answered Sep 27 '22 21:09

ams