I read many "How to kill a Thread in Java" topics and found one way is to use a boolean volatile variable to indicate whether the Thread should continue running but I've not yet seen an answer that explained how to use this variable properly in both classes (the underlying and the Runnable)
Based on my understanding right now I would do it like that:
public class Server {
private volatile boolean isRunning = true;
public Server(...) { }
public static void main(...)
...
new Thread(new Process(isRunning)).start();
...
}
public void shutdown() {
isRunning = false;
}
}
public class Process implements Runnable {
private volatile boolean isServerRunning;
public Process(boolean isServerRunning) {
this.isServerRunning = isServerRunning;
}
@Override
public void run() {
...
while(isServerRunning) {...}
...
}
}
My questions: Should I give the isRunning
variable to the Thread's Runnable as an argument like I'm doing? And also inside the Runnable class I should define this variable as a volatile? Anything else to modify to make the code better?