我已經嘗試了很多方法來解決這個問題,但我似乎無法弄清楚會解決這個問題。 當我停止遊戲時,我的遊戲線程不會停止運行!遊戲線程不會停止
(主類)
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;
}
}
我真的很糟糕的線程,以便請幫助!
你似乎也有一個無限循環'while(true)',只有在發生'InterruptedException'時纔會退出 - 如果沒有發生,則返回無限循環。 – SnakeDoc 2014-11-03 23:09:24
GUI代碼無關緊要,甚至沒有顯示嘗試停止。創建一個用於while循環的布爾值,並在需要停止時將其設置爲false。或者,您可以中斷另一個線程的線程。 – 2014-11-03 23:10:06
當玩家退出遊戲時,我希望它停止。我試着改變while循環(gameThread!= null),但它仍然不起作用。 – MCMastery 2014-11-03 23:12:21