我有一堆程序需要连续执行,直到它们全部执行,或者满足某个条件。这是在满足条件之前需要执行的基本代码:
public boolean search()
{
robot.go();
robot.spin();
//etc - around 8 more similar commands (each takes around 2 seconds)
return false; //didn't find what it was looking for
}
到目前为止,我想到做我想做的唯一方法是:
public boolean search()
{
robot.go(false);
while(robot.isMoving())
{
if(thingFound())
{
robot.stop()
return true;
}
Thread.yield();
}
robot.spin(false);
while(robot.isMoving())
{
if(thingFound())
{
robot.stop()
return true;
}
Thread.yield();
}
//etc - around 8 more similar commands
return false; //didn't find what it was looking for
}
false
参数 togo()
和指示它们应该立即返回,spin()
以便检查条件。然而,这种方法让我觉得效率很低,因为同一个代码块必须重复 10 次。这可以通过异常或并发线程更有效地实现吗?