在同一个对象上同步两次? [英] Synchronising twice on the same object?

查看:190
本文介绍了在同一个对象上同步两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如果在Java中,如果我在同一个对象上同步两次,我会得到任何奇怪的行为吗?

I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

场景如下

pulbic class SillyClassName {

    object moo;
    ...
    public void method1(){
        synchronized(moo)
        {
            ....
            method2();
            ....
        }
    }

    public void method2(){
        synchronized(moo)
        {
            doStuff();
        }
    }
}

两种方法都使用对象和是同步的。第一种方法调用的第二种方法会因为它被锁定而停止吗?

Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?

我不这么认为,因为它是相同的线程,但我不确定是否有其他奇数可能发生的结果。

I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.

推荐答案

可重入



同步块使用 reentrant 锁,这意味着如果线程已经拥有锁,它可以毫无问题地重新获取它。因此,您的代码将按预期工作。

Reentrant

Synchronized blocks use reentrant locks, which means if the thread already holds the lock, it can re-aquire it without problems. Therefore your code will work as you expect.

请参阅 Java教程页面内在锁定和同步

报价截至2015-01 ...

To quote as of 2015-01…


可重入同步

回想一下,线程无法获取另一个线程拥有的锁。但是一个线程可以获得它已经拥有的锁。允许线程多次获取同一锁定可启用可重入同步。这描述了一种情况,其中同步代码直接或间接地调用也包含同步代码的方法,并且两组代码使用相同的锁。在没有可重入同步的情况下,同步代码必须采取许多额外的预防措施,以避免线程导致自身阻塞。

Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

这篇关于在同一个对象上同步两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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