Answer: Yes, it is possible that T2 can print x = 0. Why? because without any instructions for the compiler, for example. synchronized or volatile, bExit = true may appear before x = 1 in compiler reordering. Also x = 1 may not become visible in Thread 2, so Thread 2 will load x = 0. Now, how do you fix this? When I asked this question to two programmers, they answer differently, offering to make both threads synchronized according to the general mutex, and the other said that both variables are unstable. Both are correct as this will prevent reordering and guarantee visibility. But the best answer is that you just need to make bExit as volatile, then Thread 2 can only print "x = 1". x does not have to be volatile because x cannot be reordered to come after bExit = true when bExit is unstable.
source share