1

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?

feixueck
  • 11
  • 2
  • 1
    Non-volatile fields usually get cached at some point by the JVM , so one thread may not see that such a field has been modified by another thread. – Arnaud Feb 21 '18 at 13:27
  • @Berger i know this , my confuse is why when i do nothing in while loop, it use cached value,when when i have some code in while loop, it seems the thread can get new value ? thx for your help. – feixueck Feb 21 '18 at 13:40
  • Slightly related, you may be interested in this question : https://stackoverflow.com/questions/21583448/what-can-force-a-non-volatile-variable-to-be-refreshed – Arnaud Feb 21 '18 at 13:49
  • Your claim is not correct. Regardless of `Thread.sleep(1);` commented or not, the program runs through. – Chris311 Feb 26 '18 at 09:11

0 Answers0