jeudi 14 juillet 2016

java: stop thread on ESC

I am writing a simple game in Java, and I have a following issue:

I have a controlling class, called MainGameFrame, in which there is initialized gameThread. MainGameFrame has a key listener for Esc key, so that it pauses/resumes gameThread. However, this doesn't work:

public void keyPressed(KeyEvent e) {
    // pause the game
    synchronized(gameThread) {
        if(e.getKeyCode() == e.VK_ESCAPE) {
            try {
                if(gameThread.getState() == Thread.State.WAITING) {
                    System.out.println("continue");
                    gameThread.notify();
                    System.out.println("after continue");
                } else {
                    System.out.println("pause");
                    gameThread.wait();
                    System.out.println("after pause");
                }
            } catch (InterruptedException ex) {
                    Logger.getLogger(MainGameFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

It will pause on Esc and output "pause", but not "after pause".

Aucun commentaire:

Enregistrer un commentaire