public class TestCodeSort {
private static int x = 0, y = 0;
private static int a = 0, b = 0;
// 添加volatile關鍵字禁止指令重排
// private static volatile int a = 0, b = 0;
static Object object = new Object();
public static void main(String[] args) throws InterruptedException {
int i = 0;
for (; ; ) {
i++;
x = 0;
y = 0;
a = 0;
b = 0;
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
// 這個值需要根據自己的機器去試,盡可能的使兩個執行緒的代碼執行時間一致
shortWait(32700);
a = 1;
// 如果不添加volatile關鍵字,可以通過UnSafe添加記憶體屏障
x = b;
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
b = 1;
y = a;
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
/*
* 由于a = 1;b = 1;操作分別在 x = b; y = a;操作的前邊,正常情況下是不可能出現(0,0)這種情況
*
* 出現這種情況說明y = a;或者x = b;在b = 1;或者a = 1;之前執行的
*
* 也就是說CPU或者JIT進行了指令重排
*/
String result = "第" + i + "次 (" + x + ", " + y + ")";
if (x == 0 && y == 0) {
System.err.println(result);
break;
} else {
System.out.println(result);
}
}
}
private static void shortWait(int interval) {
long start = System.nanoTime();
long end = start;
while (end - start < interval) {
end = System.nanoTime();
}
}
}
為什么這個地方 thread1.join();
thread2.join();
后面輸出x和y的值依舊會出現0,0的情況呢?
各位大佬,求解答
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/87437.html
標籤:Java相關
下一篇:求JAVA大佬解答
