谁能解释一下这些例子之间的区别是什么?
示例 # 1.
public class Main {
private Object lock = new Object();
private MyClass myClass = new MyClass();
public void testMethod() {
// TODO Auto-generated method stub
synchronized (myClass) {
// TODO: modify myClass variable
}
}
}
示例 # 2.
package com.test;
public class Main {
private MyClass myClass = new MyClass();
private Object lock = new Object();
public void testMethod() {
// TODO Auto-generated method stub
synchronized (lock) {
// TODO: modify myClass variable
}
}
}
如果在修改变量时需要注意同步,应该用什么作为监视器锁呢?
最佳答案
假设 Main
不是一个“有漏洞的抽象”,这里是第一个和第二个示例之间的最小差异。
使用 Object
可能比其他类更好,因为 Object
实例没有字段,因此更小。 Object
-as-lock 惯用语清楚地表明 lock
变量仅用作锁。
话虽如此,锁定一个其他任何东西都看不到的对象绝对有优势。 Main
方法在 Main
(例如 this
)上同步的问题在于,其他不相关的代码也可能出于不相关的目的在其上同步.通过同步专用(私有(private))锁对象,您可以避免这种可能性。
回应评论:
There is a MAJOR difference in the two cases. In the first you're locking the object that you want to manipulate. In the second you're locking some other object that has no obvious relationship to the object being manipulated. And the second case takes more space, since you must allocate the (otherwise unused) Object, rather than using the already-existing instance you're protecting.
我认为您做出了错误的假设 - MyClass
是需要保护的数据结构。事实上,问题并没有这么说。实际上,该示例的编写方式暗示该锁旨在保护整个 Main
类……而不仅仅是其状态的一部分。在这种情况下,存在明显的联系......
唯一最好锁定 MyClass
的情况是 Main
是一个允许其他代码获取其 的泄漏抽象我的类
引用。那将是糟糕的设计,尤其是在多线程应用程序中。
根据修订历史,我很确定这不是 OP 的意图。
关于java - 我应该在 Java 中使用什么作为同步语句的锁定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14735500/