gpt4 book ai didi

java - 在同步入口、导出和 volatile 读写时缓存刷新

转载 作者:行者123 更新时间:2023-12-03 23:13:18 25 4
gpt4 key购买 nike

当 synchronized block 执行完成时,所有处理器缓存都被刷新,还是只有 synchronized 语句作用于的对象被刷新?在下面的例子中,当thread执行完method2时,obj2的数据是否也刷新到主存?

class cls1 {
int x=10;
}

class cls2{
int y=10;
}

class cls3{
cls1 obj1;
cls2 obj2;
public void method2(){
obj2.y=10;
synchronized(obj1){
obj1.x=30;
}
}

public static void main(String[] args) {
final cls3 obj3 = new cls3();

Thread thread1 = new Thread(){
public void run(){
obj3.method2();
}
};
Thread thread2 = new Thread(){
public void run(){
System.out.println(obj3.obj1.x);
}
};
}
}

最佳答案

只有当另一个线程也同步第一个线程更新内容所使用的锁时,才会在关系建立之前发生。

Happens before

在此示例中,线程 B 在获取同一对象 M 上的锁后,将能够看到在同步块(synchronized block)之前和期间所做的所有更改。但请注意,必须为 happens-before 关系获取锁。

在您的示例中,因为 System.out.println(obj3.obj1.x); 未打印在同步块(synchronized block)内,因此不能保证之前发生。

引用资料:

编辑:Peter 的出色回答 What is the scope of memory flushed or published to various threads when using volatile and synchronized?

关于java - 在同步入口、导出和 volatile 读写时缓存刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38994749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com