簡體   English   中英

同步是否允許在同步方法調用后查看所有變量?

[英]Does synchronization allow visibility to all variables after synchronized method call?

public class Test {
int a = 0;
int b = 0;

public synchronized void setAB(int a, int b) {
    this.a = a;
    this.b = b;
}

public synchronized int getA() {
    return a;
}

public int getB() {
    return b;
}

線程 1 調用 setAB(1,5) - 原子地設置 a 和 b 的值。

線程 2 調用 getA() - 同步訪問。 這個調用建立發生在與上面的關系之前。 線程應該能夠看到 a 的更新值。

線程 2 調用 getB() - 這是非同步調用。 它會看到 b ie 5 的更新嗎?

一般來說,對於 getB() 調用,沒有“在關系之前發生”,也沒有可見性保證。 同步讀取和寫入並在同一個鎖上同步它們很重要。

但是,如果在同一線程中在 getA() 之后調用 getB(),則“發生在關系之前”已經建立,並且該線程可以保證看到所有更改。

在這里解釋(我特別強調):

監視器的解鎖(同步塊或方法退出)發生在同一監視器的每個后續鎖(同步塊或方法入口)之前。 並且因為happens-before 關系是可傳遞的,線程在解鎖之前的所有操作都發生在該監控的任何線程鎖定之后的所有操作之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM