Java 可重入锁问题
ringa_lee
ringa_lee 2017-04-17 16:14:44
0
1
654

看《并发编程实战》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对象的锁吗?

ringa_lee
ringa_lee

ringa_lee

reply all(1)
黄舟

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对象

这个描述显然错了,但是又不能说他错,因为子类对象同时也是一个父类对象,所以把LoggingWidget对象说成Widget对象

And an object will only have one this, that is itself. Therefore, this in the doSomething() method in the subclass and the parent class are both objects of the subclass LoggingWidget. Therefore, both methods lock the LoggingWidget object, not the Widget object mentioned in the book. 🎜 🎜This description is obviously wrong, but it cannot be said that it is wrong, because the subclass object is also a parent class object, so the LoggingWidget object is said to be a Widget 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. 🎜
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template