Java 同步引用
我有一个 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 的列表的引用上同步。我认为是后者,但需要一些帮助。
如果是这样,那么我如何完成与此类似的实际可行的事情?
谢谢!
I have a class A and 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
}
}
}
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它在 A 的列表上同步。 B 引用 A 的列表是什么意思?无论您是在 A 中使用 list 还是在 B 中使用 A.getList(),它们都引用同一个对象。当您对其进行同步时,您将阻止其他线程在同一对象上同步,无论它是从何处引用的。
It synchronizes on A's list. What do you mean by B's reference to A's list? It doesn't matter if you're in A using list or B using A.getList(), they both reference the same object. When you synchronize on it you'll block other threads from synchronizing on that same object, regardless of where it's referenced from.
OP 随后发表了这样的评论:
问题中的代码不会发生这种情况。
但如果
A
中有一个setList
方法更新了list
变量,则可能会发生这种情况。然后,您可能会遇到两个线程锁定不同对象的情况。另一种可能性是,实际上只有一个线程两次锁定同一个对象。这是正常行为。 Java 原始互斥体是可重入的;即它们仅防止两个不同线程同时持有相同的互斥锁。
The OP followed up with this comment:
That can't happen with the code in the question.
But it could happen if there was a
setList
method inA
that updated thelist
variable. You could then end up in a situation where the two threads were locking on different objects.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.