java 等待,如何使Java等待方法完成才能继续?

博客讨论了在Java中如何确保方法按特定顺序执行。作者遇到了一个问题,即需要多个方法依次运行,但不清楚如何实现方法间的等待。解决方案是引入锁的概念,通过`synchronized`关键字同步方法,使得每个方法在获取锁并执行完毕后释放锁,从而实现顺序执行。这有助于避免线程并发导致的执行顺序混乱问题。
摘要由CSDN通过智能技术生成

So my problem is that I need these methods to run one after another but I cannot work out how to make the methods wait before being run.

Any help is appreciated. Thank you.

Here is my code:

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();

解决方案

The easiest solution might be to not use threads, but i doubt that is what you want.

What you might be looking for is the concept of locks:

A method may acquire the lock associated with an object by calling:

synchronized(nameOfTheLockObject) {

//do some code here

}

This acquires the lock of the given Object, executes the code and releases the lock afterwards. If the lock is already acquired by another method/thread, the code pauses until the lock is released by the other method/thread.

You can also add the synchronized statement to methods of a class to make them acquire the lock of the parent object.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值