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?