看《并发编程实战》P21页里说以下代码:
由于Widget和LoggingWidget中执doSomething方法都是synchronized方法,因此每个doSomething方法在执行前都会获取Widget的锁。
public class Widget {
public synchronized void doSomething() {
// do somethig here...
}
}
public class LoggingWidget extends Widget {
public synchronized void doSomething() {
System.out.println(toString() + ": calling doSomething");
super.doSomething();
}
}
为什么LoggingWidget上的doSomething方法会获取Widget的锁?不是应该获取的LoggingWidget对象的锁吗?
Update:
After carefully reading the examples and the description in the original text, I feel that the author made a mistake. First of all, the synchronization method locks
this
, that's for sure.this
,这一点是肯定的。而一个对象只会有一个
this
,那就是它自己。所以子类和父类中的doSomething()
方法中的this
都是子类LoggingWidget
的对象。因此,两个方法锁住的都是LoggingWidget对象
,而不是书里所说的Widget对象
。这个描述显然错了,但是又不能说他错,因为
And an object will only have one子类对象同时也是一个父类对象
,所以把LoggingWidget对象
说成Widget对象
this
, that is itself. Therefore,this
in thedoSomething()
method in the subclass and the parent class are both objects of the subclassLoggingWidget
. Therefore, both methods lock theLoggingWidget object
, not theWidget object
mentioned in the book. 🎜 🎜This description is obviously wrong, but it cannot be said that it is wrong, because thesubclass object is also a parent class object
, so theLoggingWidget object
is said to be aWidget object
There is no grammatical error in this sentence. However, this description is obviously wrong (at least it shouldn't be) when talking about synchronization methods here. It should be due to the author's negligence or a mistake in printing. 🎜