我已经尝试了很多方法来解决这个问题,但我似乎无法弄清楚会解决这个问题的方法。 当我停止游戏时,我的游戏线程不会停止运行!
(主要课程)
public class Game extends JFrame implements Runnable {
private static final long serialVersionUID = 4662621901369762109L;
public static final Rectangle windowSize = new Rectangle(800, 600);
public static final int fps = 60;
private static Game instance;
private static Thread gameThread;
public static final PaintCanvas canvas = new PaintCanvas();
public Game() {
this.setSize(windowSize.getWidth(), windowSize.getHeight());
this.setTitle("Test");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
this.add(canvas);
Spawner mainSpawner = new Spawner();
mainSpawner.setPosition(new Point(windowSize.getWidth() / 2 - 30, windowSize.getHeight() / 2 - 30));
}
public static void main(String[] args) {
instance = new Game();
gameThread = new Thread(instance);
gameThread.start();
}
public void run() {
while (true) {
update();
try {
// 1000 divided by fps (for 60 fps, it is 16.666 repeating)
Thread.sleep(1000 / fps);
}
catch (InterruptedException e) {
break;
}
}
}
private static void update() {
for (GameObject g : new ArrayList<GameObject>(GameObjectManager.getGameObjects())) {
g.update();
}
canvas.repaint();
}
public static Game getInstance() {
return instance;
}
}
我对线程非常不好,所以请帮助!
答案 0 :(得分:0)
一些事情:
interrupt()
所以我不确定为什么你会期望在主线程结束时发生InterruptedException
。这不会发生。Timer
或ScheduledExecutorService
进行更新,而不是创建新的Thread
,因为它通常会更容易管理。以最基本的形式终止线程的更常见方式是:
volatile boolean stopMyThread = false;
public void run() {
while (!stopMyThread) {
}
}
然后当你想要阻止它时:
stopMyThread = true;
并且可选择加入线程以等待它停止。
但是,使用Timer
或更好的ScheduledExecutorServices
,您可以稍微简化一下代码。