2

I have simple program that runs background thread:

private static boolean isRunning = true;
public static void main(String[] args) throws InterruptedException {
    Thread bgThread = new Thread(() -> {
        int i = 0;
        while (isRunning) {
            i++;
        }
    });
    bgThread.start();
    TimeUnit.SECONDS.sleep(1);
    isRunning = false;
}

Due to no synchronization on isRunning variable, this program never ends on my computer. Background thread goes forever. That is understandable, but when i add System.out.println(i) instruction inside Runnable task, it stops after 1 second!

Thread bgThread = new Thread(() -> {
    int i = 0;
    while (isRunning) {
        i++;
        System.out.println(i);
    }
});

Why does this instruction causes background thread to notice update of isRunning variable? I would appreciate explanation to this one :)

Mershel
  • 542
  • 1
  • 9
  • 17

0 Answers0