尽管条件值更改,while循环也不会停止 [英] While loop not stopping despite condition value changing

查看:78
本文介绍了尽管条件值更改,while循环也不会停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

方法 Open()返回布尔变量<$ c的值理发师类中的$ c>打开。 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.

这篇关于尽管条件值更改,while循环也不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆