同步方法调用后同步是否允许所有变量可见?

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;
}

Thread-1 调用 setAB(1,5) - 自动设置 a 和 b 的值。

Thread-2 调用 getA() - 同步访问。这个电话建立发生在与上述关系之前。线程应该能够看到 a 的更新值。

线程 2 调用 getB() - 这是非同步调用。它会看到 b 即 5 的更新吗?

一般来说,getB() 调用没有 "happens before relationship",没有可见性保证。同步读取和写入很重要,并且在同一个锁上同步它们

但是,如果在同一个线程中在 getA() 之后调用 getB(),则 "happens before relationship" 已经建立,线程保证可以看到所有更改。

解释here(我特别强调):

An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor. And because the happens-before relation is transitive, all actions of a thread prior to unlocking happen-before all actions subsequent to any thread locking that monitor.