Date: 2015sep17
Update: 2025sep24
Language: Java
Q. Java: Setup a flag variable to tell a thread to stop
A. There are two ways: volatile and AtomicBoolean.
If only the parent thread sets the flag then volatile is ok.
Declare like this:
class Demo {
volatile boolean vbKeepRunning = true;
void myThread1() {
while (vbKeepRunning) {
// Do things
}
}
}
Or
import java.util.concurrent.atomic.AtomicBoolean;
class Demo {
AtomicBoolean abKeepRunning = new AtomicBoolean(true);
void myThread2() {
while (abKeepRunning.get()) {
// Do things
}
}
}