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/