在“this”上使用synchronized 之间的区别和一个私有的“新对象”?
下面的2个代码块会达到相同的结果吗?如果有的话,有什么更好的区别?
class test {
Object obj = new Object();
void test(){
synchronized(obj){
}
}
void test1(){
synchronized(this){
}
}
}
Will following 2 code block achieve the same result. What is the difference better then, if any?
class test {
Object obj = new Object();
void test(){
synchronized(obj){
}
}
void test1(){
synchronized(this){
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,他们不做同样的事情。其中一个获取“this”上的监视器,另一个获取 obj 引用的对象上的监视器。
通常,最好使用私有变量进行同步,永远不要将该变量值暴露给任何其他代码。这意味着您知道类中的代码是唯一将在该对象上同步的代码,这使您的代码更易于推理。如果您在其他代码也可以同步的任何监视器上进行同步(包括
this
引用),则在考虑线程安全、死锁等时,您需要考虑更多代码。No, they don't do the same thing. One of them acquires the monitor on "this", and the other acquires the monitor on the object referred to by
obj
.Normally it's a better idea to synchronize using a private variable, never exposing that variables value to any other code. That means you know that the code in your class is the only code which will be synchronizing on that object, which makes your code easier to reason about. If you synchronize on any monitor which other code could also synchronize on (including the
this
reference) you've got much more code to reason about when considering thread safety, deadlocking etc.