考慮以下簡單的 Java 應用程式:
public class Main {
public int a;
public volatile int b;
public void thread1(){
int b;
a = 1;
b = this.b;
}
public void thread2(){
int a;
b = 1;
a = this.a;
}
public static void main(String[] args) throws Exception {
Main m = new Main();
while(true){
m.a = 0;
m.b = 0;
Thread t1 = new Thread(() -> m.thread1());
Thread t2 = new Thread(() -> m.thread2());
t1.start();
t2.start();
t1.join();
t2.join();
}
}
}
問題:讀入區域變數是否可能導致thread1::b = 0and thread2::a = 0?
我無法證明從 JMM 的角度來看它不會發生,所以我開始分析x86-64.
以下是編譯器最終得到的 for 方法thread1和thread2(與 while 回圈無關的代碼以及-XX: PrintAssembly為簡單起見省略生成的一些注釋):
thread1:
0x00007fb030dca235: movl $0x1,0xc(%rsi) ;*putfield a
0x00007fb030dca23c: mov 0x10(%rsi),%esi ;*getfield b
thread2:
0x00007fb030dcc1b4: mov $0x1,
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/503875.html
