Let's say I have a thread including while loop and I want to stop it "from outside".
public class MyThread extends Thread {
private boolean running = true;
@Override
public void run() {
while (running) {
// do something
}
}
public void setRunning(boolean running) {
this.running = running;
}
}
And here is the Main class:
public class Main {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
// do something
mt.setRunning(false);
}
}
It seems to be stopping properly, but I have read that the boolean should be also volatile. Why? Will it quicken the stopping?