While loop not stopping despite condition value changing

心已入冬 提交于 2019-12-11 07:38:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!