我的问题是我需要这些方法按顺序运行,但我不知道如何使方法在运行之前等待。
任何帮助都受到赞赏。谢谢。
以下是我的代码:
public void startMoving() throws InterruptedException
{
moveEnemy("right",3);
wait();
moveEnemy("down",3);
wait();
moveEnemy("right",2);
wait();
moveEnemy("up",1);
wait();
moveEnemy("right",2);
wait();
moveEnemy("up",2);
wait();
moveEnemy("right",2);
wait();
moveEnemy("down",4);
wait();
moveEnemy("left",1);
wait();
moveEnemy("down",2);
wait();
moveEnemy("right",3);
wait();
moveEnemy("up",2);
wait();
moveEnemy("right",1);
wait();
moveEnemy("up",1);
wait();
moveEnemy("right",3);
}
public void moveEnemy(final String direction, final int numMoves)
{
Thread moveThread = new Thread(new Runnable()
{
public void run()
{
isMoving = true;
int originalX = getX();
int originalY = getY();
for(int loop = 0; loop <= 98*numMoves; loop++)
{
try
{
Thread.sleep(5);
}
catch (InterruptedException e){}
if(direction.equals("up"))
{
setLocation(originalX,originalY+loop);
}
if(direction.equals("down"))
{
setLocation(originalX,originalY-loop);
}
if(direction.equals("left"))
{
setLocation(originalX-loop,originalY);
}
if(direction.equals("right"))
{
setLocation(originalX+loop,originalY);
}
}
try
{
Thread.sleep(50);
}
catch (InterruptedException e){}
notify();
}
});
moveThread.start();
Thread.sleep()
。Thread.sleep()
存在各种问题,包括不精确。如果您需要精确触发方法,则可能值得检查ScheduledExecutorService
和/或Quartz
库。 - SnakeDocThread
呢?你是想让操作在 EDT 之外但按顺序执行吗?那么你只需要一个Thread
,而不是现在每个操作都有一个。 - Hauke Ingmar Schmidt