简体   繁体   English

全局变量仅会瞬时更改,这是因为同时进行读/写吗?

[英]Global variable changes only momentarily, is this because of simultaneous read/write?

I have a global variable and multiple threads which are consistently reading the variable every few seconds. 我有一个全局变量和多个线程,它们每隔几秒钟会不断读取该变量。

Now I have a method in one thread which writes to the variable, and when I print out the global variable within the function where I am writing to it, I see the write has taken place and the variable value is changed as desired. 现在,我在一个线程中有了一个写入变量的方法,当我在要写入该函数的函数中打印出全局变量时,我看到写入已发生,并且变量值已按需更改。

But when I read from outside the scope of the function immediately after it executes, the global variable has in fact not changed, and the write has not been successful. 但是,当我在函数执行后立即从函数范围之外进行读取时,实际上全局变量没有更改,并且写入未成功。

Does it sound like this is due to simultaneous read/write? 听起来像是由于同时读取/写入? I'm thinking there is something going on I don't understand, though intuitively I can't see how multithreading would change anything as the global variable is being changed at least momentarily. 我在想有些事情我不理解,尽管直觉上我看不到多线程将如何改变任何事情,因为全局变量至少暂时改变的。

No writes are happening other than the one mentioned. 除了提到的以外,没有其他写操作发生。

I haven't read up on multithreading too much so I just want a high-level "yes this is possible and makes sense with multithreading and global variables" and I will read up as necessary. 我还没有对多线程进行过多的阅读,所以我只想高层次的“是的,这是可行的,并且对多线程和全局变量有意义”,我将在必要时进行阅读。

Without seeing the actual code I can smell the problem, just use volatile in front of your global static variable and see the magic. 在没有看到实际代码的情况下,我闻到了问题,只需在全局静态变量前面使用volatile并查看魔术。 Problem solved. 问题解决了。

More information can be found at Volatile vs static 有关更多信息,请参见挥发性与静态

Are you sure you don't have two variables with the same name? 您确定没有两个具有相同名称的变量吗?

I print out the global variable within the function where I am writing to it, I see the write has taken place...But when I read from outside the scope ... the global variable has in fact not changed. 我在要写入的函数中打印出全局变量,我看到写入已经发生了……但是当我从范围之外进行读取时……实际上,全局变量没有改变。

That's what I would expect if your function declared a local variable with a name that shadows the global. 如果您的函数声明的局部变量的名称遮盖了全局变量,那就是我所期望的。

You should declare your variable as volatile as well as synchronize access to it. 您应该将变量声明为volatile并同步对其的访问。 The following code is an example to prevent collisions between threads to access myVariable. 以下代码是防止访问myVariable的线程之间发生冲突的示例。

public class ChangeVariable {
    static volatile int myVariable;
    static final Object lock = new Object();

    public static void setVariable(int value) {
        synchronized (lock) {
            myVariable = value;
        }
    }

    public static int getVariable() {
        synchronized (lock) {
            return myVariable;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM