I was asked at the interview what will be printed following this code:
static int x = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100; i++) {
x++;
}
};
final Thread thread1 = new Thread(task);
final Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(x);
I answered that it's 200. I checked in IDE and it's right. But interviewer asked about atomic operation of x++ and why the answer is 200. Where is a trick?