I was reading Effective Java and I came across this example. Item 78: Synchronize Access to Shared Mutable Data. I was trying out the example which Bloch provided, this is the example
public class Pro{
private static boolean stop;
public static void main(String arg[]) throws InterruptedException {
Thread thread = new Thread(() -> {
int i=0;
while(!stop){
i++;
}
});
thread.start();
TimeUnit.SECONDS.sleep(1);
stop=true;
}
}
As per the description this code keeps on running and never stops, but when I added a System.out.println(i) after the i++, the program actually terminated after a second. Any idea why?