Felipe Antonio
Felipe Antonio

Reputation: 29

How to destroy a thread?

I'm making simple game, here is the code:

public class Game extends Canvas implements Runnable {


public void start() {
    t = new Thread(this);
    t.start();
}

@Override
public void run() {
    setVisible(true); // visibility of the thread turn on

    while (!t.isInterrupted()) {
        if(condition for end the game) {
            t.interrupt(); //here i need to destroy the thread
            setVisible(false); //visibility to off
        }
        update();
        render();
        try {
            Thread.sleep(20);
        } catch(InterruptedException e) {}
    }
}

}

I have another class which extends JFrame and this class is introducing main menu, if my "condition for end the game" is true, the thread dissapears and the menu is visible again, its good, but if i want to start new game again, the behavior of the thread is strange- its seems like the Thread.sleep() method changed from 20 to 10 because all its going faster, probably i need to kill the thread, but i dont know how, thanks

Upvotes: 1

Views: 1936

Answers (3)

croraf
croraf

Reputation: 4720

Not really on-topic, but I'm making a game too, and for pacing I'm using Timer (from swingx):

public class MainGameLoop implements ActionListener{
     Timer timer; 
     public static void main(...){
          timer = new Timer(10, this);
      timer.start();
     }

     public void actionPerformed(ActionEvent e) {
         ...
     }
 }

Working well to me.

Upvotes: 0

TwoThe
TwoThe

Reputation: 14269

The easiest way to terminate a Thread is to exit the run function. There is no special handling required, a simple return does the trick.

For you game you might want to consider using a ScheduledExecutorService, which allows you to schedule a Runnable to run at a fixed rate:

executor.scheduleAtFixedRate(gameLoop, 0, 1000/TARGET_FPS, TimeUnit.MILLISECONDS);

Keep in mind that you then need to take out the actual looping of your gameLoop, because that is done by the fixed-rate calling, which will reduce it to:

public void run() {
  if (pause == false) {
    update();
    render();
  }
}

Where pause is a boolean should you for some reason want to put the rendering on pause for a while.

With this setup you can terminate the game simply by calling executor.shutdown() which will then suppress any further calls to the runnable.

Upvotes: 0

Maurício Linhares
Maurício Linhares

Reputation: 40333

Simple, break the loop:

    if(condition for end the game) {
        t.interrupt(); //here i need to destroy the thread
        setVisible(false); //visibility to off
        break;
    }

You end the loop and the thread will end.

Upvotes: 2

Related Questions