How to make Java wait for the method to complete before continuing?

So, my problem is that I need these methods to run one by one, but I can’t decide how to make the methods wait until it starts. Any help is appreciated. Thank. 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();
+1
source share
3 answers

The easiest solution is not to use threads, but I doubt that this is what you want.

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

A method can get the lock associated with an object by calling:

synchronized(nameOfTheLockObject) {
    //do some code here
}

, . /, , /.

, .

: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

+6

Thread.sleep(timeInMiliseconds) . , , , .

+1
boolean move = moveEnemy("right",3);
//will execute the boolean method moveEnemy and get the response before moving on
0
source

Source: https://habr.com/ru/post/1677440/


All Articles