static int a, b = 0;
static int x, y = 0;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000000; i++) {
a = b = x = y = 0;
Thread one = new Thread(new Runnable() {
@Override
public void run() {
b = 1; //1
x = a; //2
}
});
Thread two = new Thread(new Runnable() {
@Override
public void run() {
a = 1; //3
y = b; //4
}});
one.start();
two.start();
one.join();
two.join();
System.out.println("(x,y,a,b) = " + "(" + x + "," + y + ")" + "(" + a + "," + b + ")");
if(x == 0 && y == 0 && a==1 && b ==1){
System.exit(0);
}
}
static int x, y = 0;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000000; i++) {
a = b = x = y = 0;
Thread one = new Thread(new Runnable() {
@Override
public void run() {
b = 1; //1
x = a; //2
}
});
Thread two = new Thread(new Runnable() {
@Override
public void run() {
a = 1; //3
y = b; //4
}});
one.start();
two.start();
one.join();
two.join();
System.out.println("(x,y,a,b) = " + "(" + x + "," + y + ")" + "(" + a + "," + b + ")");
if(x == 0 && y == 0 && a==1 && b ==1){
System.exit(0);
}
}
}
今天看到了上方的这一段程序, 运行后可能出现 0,0,1,1的情况。
究其原因,是编译器和处理器可能会对操作做重排序。
在run方法中,b=1与x=a没有依赖关系,即没有要求b=1一定要happen before x=a。
所以编译器和处理器可能对两个run方法都进行重排序,导致输出0,0,1,1。
注:
只有多线程情况下拆分有依赖关系的操作,才会出现重排序问题。
比如在单线程中,执行 b = 1; a = 1; x = a; y = b; 是不会有问题的。因为x=a依赖于a=1这个操作,所以不会重排序。
而在多线程中,tow线程run方法中y = b; 不知道它依赖与one线程run方法中b = 1;所以会重排序