views:

26

answers:

1

This question is related to How to Queue and Call Actual Methods... Anyway, I've decided to (after all) go with the anonymous class idea. The problem is that when I ADD my anonymous class to the linked list, it's actually calling execute() immediately... and it shouldn't be. Execute() is to be called later. Anyway, this is what I have:

private LinkedList<AgentAction> actions;
public boolean blockingSensor;

this.actions.add( new AgentAction(this) {
 public void execute() {
  //setRotationalVelocity(0);
  kinematic.setWheelsVelocity(0,0);
  this.agent.setBlockingSensors(false);
  this.agent.printLCD("Turn, blocking = "+this.agent.blockingSensor);
 }

 public Object getValue() {
  return null;
 }
});

//this is essentially the main()
public void performBehavior()
{
    //make sure to only call run() each tick, not every ms
    if ( this.oldCounter < getCounter() )
    {
        if ( !isWorking() )
        {
            run();
        }
        this.oldCounter = getCounter();
        this.actions.removeFirst().execute();
    }
}

abstract class AgentAction
{
 SimbadAgent agent;
 public AgentAction(SimbadAgent a)
 {
  this.agent = a;
 }
 public abstract void execute();
 public abstract Object getValue();
}

run() is an abstract method that is implemented by a child class. I'm just not sure why it's printing when it's added, rather than executed. I understand this would imply that performBehavior() is actually being executed multiple times rather than once per tick, but that's not the case.

A: 

The devil is in the details. There's almost certainly a bug somewhere in the code you're not showing (my guess is run), but let's address a deeper point. This code looks a LOT like there producer-consumer problem. If so, I recommend checking out java.util.concurrent: it's overflowing with concurrency-related goodness that makes things like this WAY easier than trying to roll your own. For your particular case, it looks like ScheduledExecutorService might be a good fit. If it's not exactly what you need, I still recommend poking around in the package; like I said, it's stuffed with handy things that will probably be a lot easier to work with than something you built yourself from the concurrency primitives.

Hank Gay
Thanks Hank. @Mark Peters My apologies, I'll always have a full example of what my code the next time I post. The program I'm writing is dependent upon a lot of other code and I was in the process of writing a smaller test program to post.I'm having an.. interesting time making things properly concurrent, but hey I suppose that's why it isn't easy :) Thanks again.
alleywayjack