[英]Java Game Keeps Freezing When I Start A Thread?
我正在制作一个以上模式的2D僵尸射击游戏,并且我在线程方面遇到了一些问题。 这是交易。 每当我按下空格键时,我都会让角色射击子弹。 问题是,如果您持有太空,它将发射一个,然后暂停,然后发射很多子弹。 有很多方法可以解决此问题,但是我想要这种方法,因为它为将来的更改留出了腾出空间以提高拍摄速度。 这是导致问题的线程的代码:
package threads;
import Game.GameCore;
public class Shoot extends GameCore implements Runnable {
/**
* WHEN I START THIS THREAD, THE ENTIRE GAME FREEZES, AND I DO NOT KNOW
* WHY... NEED TO FIX. IT DOES NOT FIX THE PROBLEM TO TAKE OUT THE "SHOOT"
* OR THE "SLEEP"...
*/
public void run() {
while (shooting && gameRunning) { // shooting is made true when space is
// pressed, and set false when space
// is released. gameRunning is true
// if the game is running, which it
// is. removing either of these
// doesnt work either.
player.shoot(); // player comes from the GameCore class, and
// represents the player entity. if i remove this,
// nothing changes.
try {
Thread.sleep(bulletShootSpeedMillis); // bulletShootSpeedMillis
// is equal to 1000, but
// makes no difference
// to change
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
所以这是当下的问题。 评论有点指出了它们,但是却列出了它们。 如果我删除明显的东西,例如player.shoot();
或Thread.sleep(bulletShootSpeedMillis);
甚至while循环中的某件事,都不会改变。 问题是,当我初始化线程时,
else if (key == Integer.parseInt(commands[6])) {
shooting = true;
new Thread(new Shoot()).run();
}
整个游戏停滞不前。 没有任何反应。 当我从空间开始线程时,我的游戏停滞了,我不知道为什么!!! 以前的版本:
else if (key == Integer.parseInt(commands[6])) {
player.shoot();
}
它工作正常。 请帮忙! 提前致谢! :)
编辑:感谢您的快速解答。 不用说,有简单错误的重大学习经验XD
!!
new Thread(new Shoot()).run(); // ***** !!!!
您不必通过调用run()
方法来启动Thread,因为这样做的唯一目的就是在与调用代码相同的线程中调用代码。 您可以通过调用新线程的start()
方法来start()
它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.