2014-11-03 59 views
0

我已經嘗試了很多方法來解決這個問題,但我似乎無法弄清楚會解決這個問題。 當我停止遊戲時,我的遊戲線程不會停止運行!遊戲線程不會停止

(主類)

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

你似乎也有一個無限循環'while(true)',只有在發生'InterruptedException'時纔會退出 - 如果沒有發生,則返回無限循環。 – SnakeDoc 2014-11-03 23:09:24

+0

GUI代碼無關緊要,甚至沒有顯示嘗試停止。創建一個用於while循環的布爾值,並在需要停止時將其設置爲false。或者,您可以中斷另一個線程的線程。 – 2014-11-03 23:10:06

+0

當玩家退出遊戲時,我希望它停止。我試着改變while循環(gameThread!= null),但它仍然不起作用。 – MCMastery 2014-11-03 23:12:21

回答

0

幾件事情:

  1. 是什麼讓你相信,關停主線程將中斷遊戲線程?你永遠不會在任何地方撥打interrupt(),所以我不確定爲什麼你期望當主線程結束時出現InterruptedException。這不會發生。
  2. 非守護線程將繼續運行;如果仍有非守護線程,JVM將不會關閉。如果這不是你想要的行爲。
  3. 您可能需要考慮使用TimerScheduledExecutorService作爲更新,而不是創建新的Thread,因爲它通常更容易管理。

終止線程更常用的方法,在其最基本的形式,會是這樣的:

volatile boolean stopMyThread = false; 

public void run() { 
    while (!stopMyThread) { 
    } 
} 

然後,當你想停止它:

stopMyThread = true; 

並可以選擇加入該線程以等待它停止。

但是,使用Timer或更好的方法是,可以簡化代碼。

+0

謝謝!我把它設置爲守護進程。 – MCMastery 2014-11-03 23:31:24

+0

我希望在播放器退出窗口時關閉它。 – MCMastery 2014-11-04 00:36:10

+0

到目前爲止它一直在工作 – MCMastery 2014-11-04 00:36:56