何时对同步块的更改对其他线程可见

假设我在synchronized方法中更新了两个变量的值。 退出synchronized块之前 ,同步方法中设置的新值是否可能对其他线程可见?

public synchronized void setValues(){ a=5; // assume thread is preempted after this assignment // would the value 5 be visible to other threads? // my understanding is that the values will not be flushed to // main memory until the lock is released- ie, until the synchronized // method is complete. So the changes will not be visible to other // threads even when not using synchronization b=10; } 

下面的方法同步,所以我理解该线程可能会看到陈旧的值。 我的问题是,如果线程在分配给a之后被抢占,那么变量a的新值“5”是否有可能在printValues方法中可见?

 public void printValues() { System.out.println(a + " " + b); } 

是的,在到达synchronized块的末尾之前, 可以 (但不保证)在synchronized中进行的更改是可见的。 基本上,您通常需要在读取写入数据时进行同步(在同一个锁上),以便获得一致的世界视图。

为同步提供的保证是使“做正确的事”(正确同步)正常工作 – 它们不能保证在你做不正确的事情时(在没有同步的情况下观察共享变量)进行primefaces改变。

您可以(在某种程度上)将synchronized块中的写入视为对OutputStream.write()调用,同步块的退出就像flush()调用。 当你走到街区的一半时,你写的一些数据可能已经输入到输出文件(或其他任何数据) – 但它仍然可以被缓冲。 这并不意味着如何实现内存模型,只是为了帮助您了解如何保证可见性。

synchronized不保证将立即刷新a值。 如果a是易变的话。