0
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) {
        MyObject myObject = new MyObject();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myObject.stop();
            System.out.println("Thread1 stop the loop");
        }).start();

/*        while (myObject.loop){

        }*/
        while (myObject.loop) {
            System.out.println("1");
        }

        System.out.println("Main thread exist");
    }

    public static class MyObject {
        private boolean loop = true;
        public void stop() {
            this.loop = false;
        }
    }
}


In the program above,loop is a normal variable with out volatile,if the loop is empty body

while (myObject.loop){}

The main thread cannot be stopped,but if the loop with body

        while (myObject.loop) {
            System.out.println("1");
        }

,then it is able to stop. In my opinion the main thead dont know that the variable has been changed,so it should not stop. But why does the second loop end?

Gloduck
  • 11
  • 3
  • That's the meaning of "unpredictable" behaviour :-) But likely the first case only read `loop` once since it "clearly" cannot change, but the second case did not include that optimization across the method call, and re-reads `loop` every time. – iggy Jun 20 '21 at 19:13

0 Answers0