在不同的对象可见性上同步 [英] synchronize on different object visibility

查看:50
本文介绍了在不同的对象可见性上同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码显示了与此不同对象的同步:

the following code shows synchronization on different object than this:

public class A {

int a,b,c,d;

public void method1(Object x){
   synchronized(x){
     // is a ,b ,c ,d guarantee visibility ? 
   }
}

   public synchronized void method2() {
        a++;
    }
}

我知道编辑 a、b、c、d 会出现问题,因为在 method1 和 method2 中有不同的锁定,但问题是 method2 刷新的更改对 method1 是否可见?因为他们不使用相同的锁.

I know there will be a problem to edit a , b ,c ,d with having different lock in method1 and method2 , but the question is the changes flushed by method2 be visible to method1? because they don't use the same lock.

推荐答案

如果你只阅读 a,在 x64 上这会发生,因为内存屏障不限于特定的内存位置.但是,我的理解是 Java 不保证这将是线程安全的,因为锁适用于不同的对象.当然,如果你在第一个方法中增加 a ,它就不是线程安全的.

If you only read a, on x64 this will happen to work as memory barriers are not limited to specific memory locations. However, my understanding is that Java doesn't guarantee this will be thread safe as the locks apply to different objects. Certainly, if you increment a in the first method, it won't be thread safe.

这篇关于在不同的对象可见性上同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆