Java:嵌套的同步块 [英] Java: Nested synchronization blocks

查看:27
本文介绍了Java:嵌套的同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Heinz Kabutz 的Java Specialist 时事通讯版本中看到了这一点,尽管 Kabutz 博士的其余(实际上是所有)文章都解释得很好且详细,但他似乎掩饰了这段代码在做什么,或者更重要的是,它的意义是什么:

I saw this in one of Heinz Kabutz's Java Specialist newsletter editions and, although the rest (and indeed, all) of Dr. Kabutz's articles are well-explained and detailed, he seemed to gloss over what this code is doing, or more importantly, what it's significance is:

public class SomeObject {
    private Object lock1;
    private Object lock2;

    public void doSomething() {
        synchronized(lock1) {
            synchronized(lock2) {
                // ...
            }
        }
    }
}

嵌套 synchronized 块的含义是什么?这对尝试 doSomething() 的不同线程有何影响?

What are the implications of nesting synchronized blocks? How does this affect different threads attempting to doSomething()?

推荐答案

需要注意两个可能的问题

There are 2 possible issues that one would have to watch out for

  1. 如果使用等待/通知,嵌套锁很容易导致死锁.这是原因的解释.http://tutorials.jenkov.com/java-concurrency/nested-monitor-lockout.html

应该注意,如果另一种方法希望锁定相同的两个对象,它们必须始终以相同的顺序进行,否则可能会出现另一种死锁情况,如本文所述:如何避免嵌套同步和由此产生的死锁

One should be wary that if another method wishes to lock the same two objects, they must always do it in the same order, otherwise there is the possibility of another deadlock situation as explained in this post: How to avoid Nested synchronization and the resulting deadlock

这篇关于Java:嵌套的同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆