gpt4 book ai didi

java - 来自不同类的同步语句

转载 作者:行者123 更新时间:2023-11-30 08:12:23 24 4
gpt4 key购买 nike

我有两个实现接口(interface) A 的类 B 和 C。在这两个类中都存在一个带有需要同步的语句的方法。我有这个:

    class B implements A {
@Override
public void method(){
//some code here
synchronized (this.getClass()) {
//some code here
}
}
}



class C implements A {
@Override
public void method(){
//some code here
synchronized (this.getClass()) {
//some code here
}
}
}

我需要同步两个类中的语句,但是 this.getClass 返回不同的类,它可以同时执行。我怎样才能以一种只会同时执行一次的方式同步这两个来自不同类的语句?

最佳答案

需要同步它们的最可能原因是它们将要访问一些公共(public)对象。如果是,则在该对象上同步。

如果没有,如果你控制接口(interface)A,你可以添加:

public static final Object LOCK = new Object();

并让它们在 A.LOCK 上同步。

关于java - 来自不同类的同步语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30515152/

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