Java 同步块是否与 "this" 和方法参数相同?
Does Java synchronized block work same with "this" and with a method parameter?
如果在同步块中使用方法参数而不是 this 关键字,Java 同步将如何运行。
public void doSomething(final MyInterface iface) {
synchronized(this) {
// ... do some work
}
}
对
public void doSomething(final MyInterface iface) {
synchronized(iface) {
// ... do some work
}
}
净效果会一样吗?
两种情况完全不同。
当您使用 synchronized
时,将在作为参数传递的对象上获得锁(监视器)。
synchronized(this)
--> 线程获得 "current" 对象上的锁。
synchronized(iface)
--> 线程获得 "iface" 对象上的锁
Will the net effect be the same?
不,效果可能完全不同。
你读过JLS
吗? this
关键字上的同步意味着对象本身的同步(调用哪个方法)。很明显,this
对象和参数引用的对象通常不是一回事。
如果在同步块中使用方法参数而不是 this 关键字,Java 同步将如何运行。
public void doSomething(final MyInterface iface) {
synchronized(this) {
// ... do some work
}
}
对
public void doSomething(final MyInterface iface) {
synchronized(iface) {
// ... do some work
}
}
净效果会一样吗?
两种情况完全不同。
当您使用 synchronized
时,将在作为参数传递的对象上获得锁(监视器)。
synchronized(this)
--> 线程获得 "current" 对象上的锁。
synchronized(iface)
--> 线程获得 "iface" 对象上的锁
Will the net effect be the same?
不,效果可能完全不同。
你读过JLS
吗? this
关键字上的同步意味着对象本身的同步(调用哪个方法)。很明显,this
对象和参数引用的对象通常不是一回事。