如果我在同一个类上同步两个方法,它们可以同时运行吗? [英] If i synchronized two methods on the same class, can they run simultaneously?

查看:173
本文介绍了如果我在同一个类上同步两个方法,它们可以同时运行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在同一个类上同步两个方法,它们可以同时在同一个对象上运行 吗?例如:

If i synchronized two methods on the same class, can they run simultaneously on the same object? for example:

class A {
    public synchronized void methodA() {
        //method A
    }

    public synchronized void methodB() {
        // method B
    }
}

我知道我无法在两个不同的线程中对同一个对象运行 methodA()两次。同样的事情在 methodB()

I know that I can't run methodA() twice on same object in two different threads. same thing in methodB().

但是我可以运行 methodB()在不同的线程上,而 methodA()仍在运行? (同一个对象)

But can I run methodB() on different thread while methodA() is still running? (same object)

推荐答案

两种方法都锁定同一个监视器。因此,您不能在不同线程的同一对象上同时执行它们(两个方法中的一个将阻塞,直到另一个完成)。

Both methods lock the same monitor. Therefore, you can't simultaneously execute them on the same object from different threads (one of the two methods will block until the other is finished).

这篇关于如果我在同一个类上同步两个方法,它们可以同时运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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