从另一个同步方法调用同步方法是否安全? [英] Is it safe to call a synchronized method from another synchronized method?

查看:90
本文介绍了从另一个同步方法调用同步方法是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果synchronized方法调用另一个synchronized方法,它是否是线程安全的?

If a synchronized method calls another synchronized method, is it thread safe?

void synchronized method1() {
     method2()
}

void synchronized method2() {
}


推荐答案

是的,当您将方法标记为 synchronized 时,您实际上是这样做的:

Yes, when you mark methods as synchronized, then you are really doing this:

void method1() {
    synchronized (this) {
        method2()
    }
}

void method2() {
    synchronized (this) {
    }
}

当线程调用从method1进入method2时,它将确保它保持对这个的锁定,它将已经,然后它可以通过。

When the thread call gets into method2 from method1, then it will ensure that it holds the lock to this, which it will already, and then it can pass through.

当线程直接进入method1或method2时,它将阻塞,直到它可以获得锁定(这个),然后就会进入。

When the thread gets directly into method1 or method2, then it will block until it can get the lock (this), and then it will enter.

正如詹姆斯布莱克在评论中所说的,你做哈哈要知道你在方法体内做了什么。

As noted by James Black in the comments, you do have to be aware with what you do inside of the method body.

private final List<T> data = new ArrayList<T>();

public synchronized void method1() {
    for (T item : data) {
        // ..
    }
}

public void method3() {
    data.clear();
}

突然之间它不是线程安全的,因为你正在寻找 ConcurrentModificationException 将来,因为 method3 是不同步的,因此线程A可以在线程B在中工作时调用method1

Suddenly it's not thread safe because you are looking at a ConcurrentModificationException in your future because method3 is unsynchronized, and thus could be called by Thread A while Thread B is working in method1.

这篇关于从另一个同步方法调用同步方法是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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