How do I make Java wait for a method to finish before continuing?(如何让 Java 在继续之前等待方法完成?)
问题描述
所以我的问题是我需要这些方法一个接一个地运行,但我不知道如何让这些方法在运行前等待.任何帮助表示赞赏.谢谢你.这是我的代码:
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.
更多信息见:http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html
这篇关于如何让 Java 在继续之前等待方法完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何让 Java 在继续之前等待方法完成?
基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01