For the following code snippet:
Point p = new Point(5, 5);
Thread t = new Thread(() -> {
while (p.x == 5) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread detected that x is changed to " + p.x);
});
t.start();
Thread.sleep(10000);
p.x = 10;
System.out.println("Main thread changed x to 10");
I get the output as follows:
Main thread changed x to 10
Thread detected that x is changed to 10
But for the following code:
Point p = new Point(5, 5);
Thread t = new Thread(() -> {
while (p.x == 5) { }
System.out.println("Thread detected that x is changed to " + p.x);
});
t.start();
Thread.sleep(10000);
p.x = 10;
System.out.println("Main thread changed x to 10");
I get only:
Main thread changed x to 10
Why is that happening?