this question is about change a variable for while ,but not valid in it . the code like below:
public class StopThreadTest extends Thread {
private boolean isStop = false;
private void setStop() {
isStop = true;
}
@Override
public void run() {
while (!isStop) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
StopThreadTest test = new StopThreadTest();
test.start();
//
Thread.sleep(2000);
test.setStop();
System.out.println(" has set stop ... ");
}}
when i run this code ,the program can terminated normally. but when i comment out the code in run method (just like below) ,the program can't terminate itseslf.
@Override
public void run() {
while (!isStop) {
try {
//when comment out the blow line ,the program will runs forever .
//Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
but when i set the variable "isStop" volatile ,the programe again run normal.
private volatile boolean isStop = false;
so, my question is : a. if not use volatile ,the variable can't read again in while loop ? but why when has an operation (such as print a word,or sleep 1 mills) in while loop,it can work normal ?
and my env is (windows 10,x64, jdk1.8)
hope anyone can help to explain this phenomenon?