java - 如果访问线程是由先前分配变量的同一线程创建的,是否需要 volatile?

标签 java multithreading thread-safety volatile

class MyClass {
    private int value;

    private void someFunction()
    {
        // value will never be assigned anywhere else while the thread is running
        this.value = 10;

        // start thread that reads value
    }
}

这是否需要 volatile 或线程是否保证看到最新值?

最佳答案

Does this requires a volatile or is the thread guaranteed to see the latest value?

不,volatile 不是必需的。该 Java 语言定义表明,在调用 start() 之前,创建的线程将看到创建线程所做的所有更新。

参见 Synchronization Order (JLS 17.4.4) .引用:

  • An action that starts a thread synchronizes-with the first action in the thread it starts.

显然,如果值在 start() 之后更新,或者如果新线程对起始线程需要看到的值进行了更改,则需要进行内存同步。

如果您调用 thread.join(),同样适用。 join() 返回后,调用者可以看到由加入的线程所做的任何更新。

关于java - 如果访问线程是由先前分配变量的同一线程创建的,是否需要 volatile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20746211/

相关文章:

c - C标准库中的函数线程安全吗?

delphi - "Double-Checked Locking"在Delphi中应该如何实现?

java - 如何使用 AudioManager 使听筒静音?

c++ - 32 位 int 类型的 Win API 互锁操作

java - 什么是最好的构造函数

c++ - 如何在 C++ 中创建多线程应用程序

c# - 了解 System.Threading.Tasks 行为

forms - 在 Delphi 中线程打开表单

java - 在 Java 中获取 Arraylist 的状态

java - arrayset 没有 Java 实现