如何在父 class 上同步嵌套的 Java class 方法?

How to syncronize nested Java class method on parent class?

我有两个classes

public class A {
    private byte[] buf;
    public synchronized void foo() {
        // does something with buf
    }
    public class B {
        public synchronized void bar() {
            // also does something with buf
        }
    }
}

据我所知,方法 bar() 在 class B 的实例上同步。如何在 class A 的对象上同步它以保护 buf?

in this answer所述,您可以执行以下操作:

public class A {
    private byte[] buf;

    public synchronized void foo() {
        // does something with buf
    }

    public class B {
        public void bar() {
            synchronized (A.this) {
                // also does something with buf
            }
        }
    }
}

这仅适用,因为您使用的嵌套 class 引用了其父项 class。但是,如果您只想同步变量 buf 的使用,您也可以这样做:

public class A {
    private byte[] buf;

    public void foo() {
        synchronized (buf) {
            // does something with buf
        }
    }

    public class B {
        public void bar() {
            synchronized (buf) {
                // also does something with buf
            }
        }
    }
}