sof sof - 5 months ago 9
Java Question

Variable unexpectedly manipulated by threads

public class Main {
static int i = 0;

public static void main(String[] args) {
for (; i < 2; i++)
new Thread(() -> System.out.println(i)).start();
}
}


I expected the code above to print out either


0

1


or


1

0


but to my surprise I got


2

2

Answer

I run the same program and it gives the same result for me too. But if you run it like that

for (; i < 2; i++) {
    Thread.sleep(10);
    new Thread(() -> System.out.println(i)).start();
}

results became

1
2

If you add Thread.sleep(10) below the new Thread(() -> System.out.println(i)).start(); it outputs

0
1

That's because of current thread(main) executes loop before the threads.

  1. Main Thread starts.
  2. Loop starts.
  3. Thread - 1 created.(Thread is still idle)
  4. Loop continuous.(i=1)
  5. Thread - 2 created.(Thread is idle)
  6. Loop ends.
  7. Main Thread ends.

Thread 1 and thread 2 starts between 2nd and 7nd step of your code. Operating system handles the thread scheduling so you can not expect the result in this program.