当易失性和非易失性字段混合时,我试图了解易失性字段的发生前行为。
假设有 1 个 WriteThread 和 5 个 ReadThreads,它们更新/读取 SharedObject。
ReadThreads 从头开始调用方法,WriteThread在 1 秒后waitToBeStopped()
调用该方法。stop()
public class SharedObject {
volatile boolean stopRequested = false;
int a = 0, b = 0, c = 0;
int d = 0, e = 0, f = 0;
// WriteThread calls this method
public void stop() {
a = 1;
b = 2;
c = 3;
stopRequested = true;
a = 4;
b = 5;
c = 6;
d = 7;
e = 8;
f = 9;
}
// ReadThread calls this method
public void waitToBeStopped() throws Exception {
while(!stopRequested) {
}
System.out.println("Stopped now.");
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + f);
}
}
当这个程序结束时,输出是这样的。即使我尝试了 100 多个 ReadThreads,结果也总是一样的。
Stopped now.
Stopped now.
Stopped now.
Stopped now.
Stopped now.
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
4 5 6 7 8 9
Q1。有人可以解释为什么这总是返回 4,5,6,7,8,9 而不是 1,2,3,0,0,0?
我对happens-before关系的理解是这样的:
- WriteThread 写入
a=1,b=2,c=3
发生在WriteThread 写入之前stopRequested
- WriteThread 写入
stopRequested
发生在WriteThread 写入之前a=4,b=5,c=6,d=7,e=8,f=9
- WriteThread 写入
stopRequested
发生在ReadThread 读取之前stopRequested
- ReadThread 读取
stopRequested
发生在ReadThread 读取之前a,b,c,d,e,f
从这 4 个陈述中,我无法得出这样的陈述……
- WriteThread 写入
a=4,b=5,c=6,d=7,e=8,f=9
发生在ReadThread 读取之前a,b,c,d,e,f
如果有帮助,这是代码的另一部分:
public class App {
public static void main(String[] args) throws Exception {
SharedObject sharedObject = new SharedObject();
for(int i =0 ; i < 5; i++) {
Runnable rThread = new ReadThread(sharedObject);
new Thread(rThread).start();
}
Runnable wThread = new WriteThread(sharedObject);
new Thread(wThread).start();
}
}
public class WriteThread implements Runnable {
private SharedObject sharedObject;
public WriteThread(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
sharedObject.stop();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class ReadThread implements Runnable {
private SharedObject sharedObject;
public ReadThread(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
try {
sharedObject.waitToBeStopped();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}