I need some help to fully understand what's happening when, running this code
public class Main extends Thread {
private static int x;
public static void main(String[] args) {
Thread th1 = new Main("A");
Thread th2 = new Main("B");
th1.start();
th2.start();
}
public Main(String n) {
super(n);
}
public void run() {
while(x<4) { //1
x++; //2
System.out.print(Thread.currentThread().getName()+x+" "); //3
}
}
}
I get the output
B2 B3 B4 A2
I understand that threads A
and B
both increment x
, then B
loops incrementing and outputting... but why is last output A2
? Shouldn't A
see x
as 4 when executing //3
?
Bonus question: why is it impossible for x
to become 5?
EDIT
This question (in a slightly different form) comes from a mock test for OCP certification, where explanation states that x
will never be 5. I'm glad to see that I'm not the only one to disagree.