尽管条件值更改,while循环也不会停止

尽管条件值更改,while循环也不会停止

问题描述:

我的 main()函数中包含以下代码行:

I have the following lines of code in my main() function:

方法 Open()返回布尔变量打开。 barber类中的run方法将 open 变量设置为true,但main函数中的while循环不会停止。尽管有变化,但这就像永远将 barber.Open()视为错误一样。
这是理发师类中的相对代码:

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 :

声明 open 字段为 volatile ,以确保一个线程中的写操作对另一线程中的读者可见:

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;

您当前的问题很可能与Java内存模型中的Happens-Before关系有关。当前,您没有使用任何会产生必要的内存屏障的指令。 volatile (这只是获取方法的一种)。 >在此答案中。如果您想更深入地阅读,请尝试关闭Java遭遇者Shipilev的内存模型种类

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.