Given this code:
public class Game implements Runnable {
private volatile boolean stop;
public Game() {
...
}
public void run() {
while(!stop) {
// play game
}
}
public void stopGame() {
stop = true;
}
}
public class Main {
public static void main(String[] args){
Game g = new Game(); // Game class implements Runnable
Thread t = new Thread(g);
t.start();
// do the two method calls below effectively do the same thing?
t.interrupt();
g.stopGame();
}
}
Does stopGame() kill the thread as effectively as using something like interrupt, or a java.lang.Thread method to kill the thread? (I'm not too familiar with how you would kill a thread using a Thread method.)
Also, in the case that stopGame() is the best way to kill a thread, is there any to call it if they only had access to the Thread instance like below:
public static void Main(String[] args){
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(new Game()));
// can you access the Game instance given the Thread instance
// or do you need to hold onto the reference of the Game instance?
threads.get(0).stopGame(); // for example, this won't work.
}