加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java中的“synchronized(this)”vs.“synchronized((BaseClass)t

发布时间:2020-12-14 16:28:44 所属栏目:Java 来源:网络整理
导读:这是我上一个问题 Is this variable being safely accessed by using synchronization?的继承人 对于以下程序, Class SubClassB extends SuperClassA { protected int c; public void inc() { synchronized (this) { c++; } } public void dec() { synchroni
这是我上一个问题 Is this variable being safely accessed by using synchronization?的继承人

对于以下程序,

Class SubClassB extends SuperClassA {
     protected int c;

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          synchronized ( (SuperClassA) this) {
               c--;
          }
     }
}

计数器“c”是否被访问线程安全?我不确定在“dec()”方法中,SuperClassA是否为“this”引用同步块的有效对象?如果是,两个同步块是否锁定相同的“this”对象? (在我看来,“(SuperClassA)这个”不等于“这个”)

这个奇怪的模拟代码来自以下现实生活中的例子,其中SuperClassA是一个不被修改的基类,

Class SuperClassA {
     protected int c;

     public void dec() {
          synchronized (this) {
               c--;
          }
     }
}

Class SubClassB extends SuperClassA {

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          super.dec();
     }
}

在这个例子中,SubClassB中的“dec()”方法调用其超类的“dec()”方法,该方法对我认为是“SuperClassA.this”的“this”对象执行锁定.如果SubClassB的“inc()”方法中的锁定对象与SubClassB的“dec()”方法中的锁定对象不完全相同,那么我想知道SubClassB中继承的计数器“c”可能不会被不同的线程安全地访问.我觉得在同步块中使用“this”引用有一些歧义.

在现实生活的例子中,如果我希望SubClassB的计数器“c”是线程安全的,那么我需要在其“dec()”方法中添加一个更多的同步块,就像这样,

Class SubClassB extends SuperClassA {

     public void inc() {
          synchronized (this) {
               c++;
          }
     }

     public void dec() {
          synchronized (this) {
               super.dec();
          }
     }
}

但似乎这样添加的块不是优雅的,可能是多余的!

有人对这些问题有一些想法.提前致谢.

劳伦斯

解决方法

Would the counter “c” be accessed thread safe ?

是的,它使用相同的锁定对象.

I am not sure that in the “dec()” method,is the SuperClassA cast “this” reference a valid object for the synchronized block ?

是.

If yes,would the two synchronized blocks lock the same “this” object ? (As it seems to me that “(SuperClassA) this” is not equal to “this”)

是.即使将实例转换为可以转换为(甚至Object)的实例,它仍将引用相同的对象.

[…] But it seems that such added block is not elegant and may be redundant !

这是多余的.仅当您调用多个同步方法并且组合效果必须为原子时,才需要额外的同步.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读