你是否锁定了它的所有方法

你是否锁定了它的所有方法

本文介绍了如果你锁定了一个对象,你是否锁定了它的所有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个对象 foo:

Say we have a object foo:

class Foo(){
  public synchronized void instanceMethod(){}
}

var foo = new Foo();

如果我锁定了 foo:

if I have a lock on foo:

synchronized(foo){
  foo.instanceMethod();
}

我是否也锁定了 instanceMethod() 调用?另一种提问方式——如果我锁定了 foo,另一个线程可以调用 foo.instanceMethod()(同时)吗?

do I also have a lock on the instanceMethod() call? Another way of asking the question - if I have a lock on foo, can another thread call foo.instanceMethod() (simultaneously)?

推荐答案

他们可以调用它,但是调用会一直等到执行离开你的块 synchronizedfoo 上,因为 instanceMethodsynchronized.声明一个实例方法 synchronized 与将其整个主体放在 this 上的 synchronized 块中大致相同.

They can call it, but the call will wait until execution leaves your block synchronized on foo, because instanceMethod is synchronized. Declaring an instance method synchronized is roughly the same as putting its entire body in a block synchronized on this.

如果instanceMethod没有同步,那么调用当然不会等待.

If instanceMethod weren't synchronized, then of course the call wouldn't wait.

但是请注意,您显示的 synchronized 块是不必要的:

Note, though, that the synchronized block you've shown is unnecessary:

synchronized(foo){       // <==== Unnecessary
  foo.instanceMethod();
}

因为 instanceMethodsynchronized,所以可以是:

Because instanceMethod is synchronized, that can just be:

foo.instanceMethod();

...除非块中还有其他东西.

...unless there's something else in the block as well.

这篇关于如果你锁定了一个对象,你是否锁定了它的所有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:25