[英]Threading and synchronisation in Java
如果类中有synchronized方法并且1个线程进入它,则另一个线程可以在不同的对象上调用相同的方法。
Yes, if the method is not static
. 是的,如果方法不是
static
。
A synchronized
non-static method synchronizes on this
. synchronized
非静态方法在this
同步。 So this method: 所以这个方法:
public synchronized void foo() {
// do stuff
}
is effectively equivalent to this one: 实际上相当于这个:
public void foo() {
synchronized(this) {
// do stuff
}
}
A static
synchronized method synchronizes on the current class. static
同步方法在当前类上同步。 So a method like this: 所以像这样的方法:
public static synchronized void bar() {
// do stuff
}
is effectively equivalent to this one: 实际上相当于这个:
public static void bar() {
synchronized(ThisClass.class) {
// do stuff
}
}
If the method is marked as synchronized
, then the lock is held on the object. 如果该方法被标记为已
synchronized
,则锁定将保留在对象上。 This means that a call to the same method on a different object will not be locked. 这意味着不会锁定对不同对象的相同方法的调用。
However, if the method is a static
one, then it is held by the entire class and it will not be possible for a second call to run it at the same time [and will be blocked] 但是,如果该方法是
static
,那么它由整个类保持,并且第二次调用不可能同时运行它[并且将被阻止]
是的,另一个线程可以从此类的实例调用此方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.