2014-11-03 6 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

또한 'InterruptedException'이 발생한 경우에만 종료되는 'while (true)'무한 루프가있는 것처럼 보입니다. 발생하지 않으면 무한 루프가됩니다. – SnakeDoc

+0

GUI 코드는 관련성이 없으므로 멈추려는 시도조차 보이지 않습니다. while 루프에 사용할 부울을 만들고, 중지 시키려면 false로 설정하십시오. 또는 다른 스레드에서 스레드를 인터럽트 할 수 있습니다. –

+0

플레이어가 게임을 종료 할 때 멈추고 싶습니다. While while (gameThread! = null) while 루프를 변경해 보았지만 여전히 작동하지 않습니다. – MCMastery

답변

0

커플 : 메인 스레드를 종료 게임 스레드 중단 될 생각한다 무엇

  1. ? 항상 interrupt()을 호출하지 않으므로 주 스레드가 끝날 때 InterruptedException이 발생할 것으로 예상되는 이유가 확실하지 않습니다. 이것은 일어나지 않습니다.
  2. 비 데몬 스레드는 계속 실행됩니다. 아직 데몬이 아닌 스레드가 있으면 JVM이 종료되지 않습니다. Set your new thread to be a daemon이 원하는 동작이 아닌 경우
  3. 일반적으로 관리하기가 더 간편하므로 Thread을 새로 만드는 대신 업데이트에 Timer 또는 ScheduledExecutorService을 사용하는 것이 좋습니다.

스레드를 종료하는 일반적인 방법은 가장 기본적인 형태로 볼 수있는 작품 같은 : 당신이 그것을 중지 할 것 그리고

volatile boolean stopMyThread = false; 

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

:

stopMyThread = true; 

그리고 선택적으로 스레드에 참여하여 스레드가 중지 될 때까지 기다립니다.

그러나 Timer 또는 더 나은 경우 ScheduledExecutorServices으로 코드를 간소화 할 수 있습니다.

+0

감사합니다. 나는 Daemon으로 설정했다. – MCMastery

+0

플레이어가 창을 나갈 때 종료하고 싶습니다. – MCMastery

+0

지금까지 작업 중입니다. – MCMastery

관련 문제