问题
I have the following lines of code in my main()
function:
The method Open()
returns the value of a boolean variable open
in the barber class. The run method in the barber class sets open
variable to true but the while loop in the main function doesn't stop. It's like it's seeing barber.Open()
as false forever, despite the change.
This is the relative code in the barber class :
回答1:
Declare the open
field as volatile
to ensure that write in one thread is visible to a reader in the other thread:
private volatile boolean open;
Your current problem is most likely related to Happens-Before relationship in Java Memory Model. Currently you are not using any instruction that would generate the necessary memory barrier. Using volatile
, which is just one of the ways to get it, is explained in detail in this answer. If you prefer a more in-depth read try Close Encounters of The Java Memory Model Kind by Shipilev.
来源:https://stackoverflow.com/questions/49481873/while-loop-not-stopping-despite-condition-value-changing