可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have an outer class A and that has a public inner class, the structure is as follows -:
public class A{ public int x; public class B{ private static final int y; } public synchronized int method1(){ return x+ B.y; } }
the question is if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?
回答1:
if I used synchronized keyword on every method of the class A will it also lock the members of the inner class as well?
No it won't.
You seem to be confused in a number of respects here.
Using a primitive mutex (e.g. via a synchronized method) only locks against other threads that are synchronizing on the same mutex.
When you call a synchronized instance method, the mutex you are acquiring is the mutex for this ... the target object.
In your example, it seems that you want to lock a static field, not an instance field.
If I understand correctly what you are trying to do, the correct way to do it is something like this:
public synchronized int method1(){ synchronized (B.class) { return x + B.y; } }
Note that this involves acquiring two mutexes, so you need to make sure that your code always acquires them in the same order. (If you don't, then there is a risk of deadlocks.)
You would get the same effect if you created and called a synchronized static method on B for getting the value of the y field.
回答2:
No, the inner class and outer class are two different class objects, they will not be the same. I suggest creating a field in the outer class to manually synchronize on.
回答3:
An example with a single mutex on 2 objects. Both Objects can change a variable x.
public class A { private Object mutex = new Object(); private int x; private B b = new B(); public class B { private int y; public int method() { synchronized(mutex) { return x++; } } } public int method() { synchronized(mutex) { return x += b.y; } } }