Java同步参考 [英] Java synchronized references
问题描述
我有A类和B类.
public class A() {
private static List<int> list = new ArrayList<int>();
public static List<int> getList() {
return list;
}
}
public class B() {
public void foo() {
synchronized(A.getList()) {
// DO Stuff
}
}
}
在我同步的B类中.这是否在A的列表上或B在对A的列表的引用上同步.我认为是后者,但可以使用一些帮助.
In class B where I synchronize. Does this synchronize on A's list, or on B's reference to A's list. I think it is the latter but could use some help.
如果是这样,那么我该如何完成与实际可行的功能类似的事情?
If so then how do I accomplish a similar thing to this that will actually work?
谢谢!
推荐答案
OP随后发表了以下评论:
The OP followed up with this comment:
我所看到的行为很奇怪,就是如果我从A内锁定,我实际上可以同时在B中锁定它.这在很大程度上意味着同步无效.这就是为什么我认为锁定参考无法正常工作的原因.
What's weird is the behavior that I am seeing is that if I lock from within A I can actually lock it at the same time in B. Which pretty much means the synchronized has no effect. Which is why I surmised that maybe locking a reference won't work.
问题代码无法实现.
但是如果A
中有一个setList
方法更新了list
变量,则可能会发生这种情况.然后,您可能会遇到两个线程锁定在不同对象上的情况.
But it could happen if there was a setList
method in A
that updated the list
variable. You could then end up in a situation where the two threads were locking on different objects.
另一种可能性是您实际上只有一个线程对同一对象进行两次锁定.这是正常现象. Java基本互斥体是可重入的;也就是说,它们仅阻止两个不同线程同时保留相同的互斥量.
Another possibility is that you actually only have one thread that is taking a lock on the same object twice. That's normal behavior. Java primitive mutexes are reentrant; i.e. they only prevent two different threads from holding the same mutex at the same time.
这篇关于Java同步参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!