“参考”上的同步或实例
考虑以下代码:
public class Foo {
private static final Object LOCK = new Object();
private Object _lockRef1 = LOCK;
private Object _lockRef2 = LOCK;
private int _indx = 0;
public void dec() {
synchronized(_lockRef1) {
_indx--;
}
}
public void inc() {
synchronized(_lockRef2) {
_indx++;
}
}
}
对 dec()
和 inc()
方法的调用是线程安全的吗?一方面,这些方法在两个不同的实例 _lockRef1
和 _lockRef2
上同步。另一方面,这些实例“指向”同一个对象LOCK
...
Consider the following code:
public class Foo {
private static final Object LOCK = new Object();
private Object _lockRef1 = LOCK;
private Object _lockRef2 = LOCK;
private int _indx = 0;
public void dec() {
synchronized(_lockRef1) {
_indx--;
}
}
public void inc() {
synchronized(_lockRef2) {
_indx++;
}
}
}
Is call to methods dec()
and inc()
threadsafe? On the one hand these methods are synchronized on two different instances _lockRef1
and _lockRef2
. On the other hand, these instances "point" on the same object LOCK
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它们不是“在两个不同的实例上同步” - 仅仅因为您使用两个不同的变量并不意味着有两个不同的实例。您有多个变量,每个变量都具有相同的值 - 对
java.lang.Object
的单个实例的引用。所以是的,这是线程安全的。当然,就可读性而言,您不应该编写这样的代码,但假设您只是想了解发生的情况,那就没问题了。
They're not "synchronized on two different instances" - just because you use two different variables doesn't mean there are two different instances. You've got several variables each of which will have the same value - a reference to the single instance of
java.lang.Object
.So yes, this is thread-safe. Of course you shouldn't write code like this in terms of readability, but assuming you're just trying to understand what happens, it's fine.