Java private method for Java supersync

I have class A and B that inherit from Base.

The base has a private method. It is possible that A and B execute this method at the same time.

So, I want to synchronize this method. If I just put the “synchronize” keyword in the signature, will this make synchronization of A and B (sharing the same lock)? Or do I need to create a static lock object ...?

Sorry, a little confused ...

+3
source share
4 answers

, , , , increment . getNewCounter. .

public class Base {
    private int counter;

    private void increment() {
        counter++;
    }
    protected int getNewCounter() {
        increment();
        return counter;
    }
}

public class A extends Base {
    public int aMethod() {
        return getNewCounter();
    }
}

public class B extends Base {
    public int anotherMethod() {
        return getNewCounter();
    }
}
+3

. , A B .

, - .

:

A B, Singleton C, C, , A B.

, : , , , , .

+2

, , . , .

, syncronized, , . - .

, ObjectA ObjectB Test, : myMethod(), Test , , .

, .

+2
source

I know that private members are NOT inherited. Thus, class A and class B cannot access this private method using inheritance or creating an object of class Base to call this method until there is a public method in the base class that has access to this private method.

0
source

All Articles