好.我编写了代码并获得了意想不到的结果,我不知道如何解释这个结果.有人可以帮我弄这个吗?
public class JMM {
static volatile Boolean ready = false;
static volatile int data = 0;
public static void main() {
Log.d("JMM", "start");
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
data = 1;
ready = true;
}
}).start();
for(int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (!ready)
Log.d("JMM", "second thread data " + data);
}
}).start();
}
}
}
我在Nexus 5上执行它(它有4个内核):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MM.main();
}
结果:
D/JMM: second thread data 0
…
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 0
D/JMM: second thread data 0
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
D/JMM: second thread data 1
我期待什么?默认情况下,int是原子类型(但之前我写过volatile)并且它没有缓存它的值.但是我看到不同的线程在同一时刻从一个字段读取不同的值.谁能向我解释一下?
最佳答案 考虑一下这行发生的事情:
Log.d("JMM", "second thread data " + data);
>读取数据
>将其转换为String并与“第二个线程数据”连接
>将两个参数传递给Log.d
>它最终打印出消息
在第一步之后会发生很多事情,并且很可能一个线程将从第一步开始,但在它之前进入第4步.例如:
Thread 1 | Thread 2
-----------------------+-----------------------
1. read "data" |
2. concat string: |
"...data 0" |
<<< third thread updates data = 1 >>>
| 1. read "data"
| 2. concat string:
| "... data 1"
| 3. invoke Log.d(...)
| 4. print message
| with "... data 1"
3. invoke Log.d(...) |
4. print message |
with "data 0" |