[英]Odd linked list/anonymous class behavior - executing when added?
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(),而不应该这样。 Execute() is to be called later.
Execute()将在以后调用。 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. run()是由子类实现的抽象方法。 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.
我知道这暗示着performBehavior()实际上实际上被执行了多次,而不是每个滴答一次,但是事实并非如此。
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. 几乎可以肯定的是,您未显示的代码中有一个错误(我的猜测是
run
),但让我们解决一个更深层次的问题。 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. 如果是的话,我建议您检查出
java.util.concurrent
:它与并发相关的善良,使事情像这样不是试图推出自己更容易溢出。 For your particular case, it looks like ScheduledExecutorService
might be a good fit. 对于您的特定情况,似乎
ScheduledExecutorService
很合适。 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.
就像我说的那样,它充满了方便的事情,比起使用并发原语自己构建的东西要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.