Nicholas Eason
Nicholas Eason

Reputation: 300

Thread.join() not working as expected

I'm using a thread to repaint a JPanel (seeing as repaint() is thread safe).

Here is the paintComponent method:

    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    //Print statement so I know where my program is at.
    System.out.println("Repainting world...");
    g.drawImage(worldImage, x, y, 6144, 4608, null);
}

I have a thread that starts inside of a KeyListener whenever a user presses a certain button

Run method:

public void run(){
                game.repaint();
}

Lastly, here's my calls to the thread that uses the above run method:

//NOTE: I've tried this without the if statement, made no difference
if(!gameThread.isAlive()){
    gameThread.start();
    try {
            gameThread.join();
    } catch (InterruptedException e) {
            e.printStackTrace();
    }
}

I'm pretty sure that, with this case (since it's in a KeyListener), Thread.join() stops the EDT until that run method is executed.

The problem is, Thread.join is throwing an InterruptedException whenever I press the button again, no matter how long I wait. This leads me to believe that somewhere it's getting hung in an area, where the thread will not stop it's execution. I just can't tell where it could potentially be getting hung up.

Upvotes: 0

Views: 410

Answers (1)

swingMan
swingMan

Reputation: 752

If I understand this...you're calling repaint() from within your gameThread. Since repaint() executes on the EDT, I think you've blocked it from executing by virtue of the fact that gameThread.join() blocks the EDT (since it's started by the EDT i.e. from within your KeyListener handler).

Upvotes: 1

Related Questions