【发布时间】:2018-01-03 14:23:12
【问题描述】:
在调用 OkHttp 时,我需要担心回调方法中的内存一致性吗?
下面是我要问的一个例子。 n 在主线程上设置为 5,并且没有其他写入 n。然后在 onResponse 中访问它,它在另一个线程上运行。当在另一个线程上读取它时,我们是否保证 n 的值为 5(如果是,为什么)?还是我们需要让 n 不稳定?
int n;
n = 5; // This is the only write to n. It happens on the main thread.
mOkHttpCall.enqueue(new Callback() {
@Override
public void onResponse(@Nonnull Call call, @Nonnull Response response) throws IOException
{
// We're not on the main thread here. Is n guaranteed to be 5?
}
});
【问题讨论】:
标签: multithreading okhttp