2

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?

Vinnie
  • 71
  • 6
  • there is no reason this program should not end once stop has been set to true. the addition of sysout(i) should not make any difference. – akshaya pandey Feb 07 '18 at 06:30
  • 2
    I would imagine that the original loop is too tight and will now yield any cpu to another thread. Putting in a mini-sleep into this loop should help. Also consider AtomicBoolean – Scary Wombat Feb 07 '18 at 06:30

0 Answers0