加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

可重入锁 – 实践中的Java并发

发布时间:2020-12-15 04:44:52 所属栏目:Java 来源:网络整理
导读:下面是一些用于“实践中的 Java并发”的重入锁定的示例代码: class Widget {public synchronized void doSomething() { System.out.println(toString() + ": calling superclass doSomething");}}class LoggingWidget extends Widget {public synchronized
下面是一些用于“实践中的 Java并发”的重入锁定的示例代码:

class Widget {
public synchronized void doSomething() {
    System.out.println(toString() + ": calling superclass doSomething");
}


}

class LoggingWidget extends Widget {
public synchronized void doSomething() {
    System.out.println(toString() + ": calling subclass doSomething");
    super.doSomething();
}
}

这本书在上面的代码中解释了……
“因为Widget和LoggingWidget中的doSomething方法都是同步的,所以每个方法都会在继续之前尝试获取Widget上的锁定.”

我运行上面的代码来观察内在锁.上面的引用似乎暗示一个线程获取Widget对象的内部锁,但我观察到的是该线程获取了LoggingWidget上的锁.我不确定如何验证采集计数,所以无法观察到.

该书是否可以互换地使用名称LoggingWidget / Widget,还是应该特意观察Widget对象的锁定?

编辑:完整摘录

Reentrancy facilitates encapsulation of locking behavior,and thus
simplifies the development of object-oriented concurrent code. Without
reentrant locks,the very natural-looking code in Listing 2.7,in
which a subclass overrides a synchronized method and then calls the
superclass method,would deadlock. Because the doSomething methods in
Widget and LoggingWidget are both synchronized,each tries to acquire
the lock on the Widget before proceeding. But if intrinsic locks were
not reentrant,the call to super.doSomething would never be able to
acquire the lock because it would be considered already held,and the
thread would permanently stall waiting for a lock it can never
acquire. Reentrancy saves us from deadlock in situations like this.

解决方法

是的,作者可以互换地使用LoggingWidget / Widget,因为根据OOP继承原则,LoggingWidget对象也是一个Widget类对象.在该示例中,将仅创建一个对象实例,并将其用作同步监视器以重新输入.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读