关于velotile的面试题,百思不得其解中,请指导
直接上代码,可以直接运行。输入结果可能有三种情况:1,1/0,0/0,1 但惟独不可能为1,0. 请问为什么。
public class VelotileTest {
public static volatile int x = 0; // Reads and writes to this variable are atomic.
public static int y = 0;
public static void executedByThread1() {
y = 1;
x = 1; // "happens before" action
}
public static void executedByThread2() {
int r1 = x;
int r2 = y;
System.out.println(r1 + ", " + r2);
}
public static void main(String... args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
executedByThread1();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
executedByThread2();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}