重排序对多线程的影响

考虑下面的代码,按照道理不可能出现x < y的情况。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Something {
private int x = 0, y = 0;

public void write() {
x = 100;
y = 50;
}

public void read() {
if (x < y)
System.out.print("x < y");
}
}

public class Test {
public static void main(String[] args) {
final Something obj = new Something();

new Thread() {
public void run() {
obj.write();
}
}.run();

new Thread() {
public void run() {
obj.write();
}
}.run();
}
}

但是在实际运行中却可能出现,主要原因就是重排序的影响。犹豫对于x的赋值和y的赋值之间不存在依存关系,编译器可能改变顺序。