简体   繁体   English

关于从同步块调用方法

[英]About calling methods from a synchronized block

Is synchronizing a method equivalent to letting only one thread to evaluate it until it's out of scope including inner method calls? 正在同步一个等价的方法,只让一个线程对它进行评估,直到它超出范围,包括内部方法调用?

For example: 例如:

public synchronized void foo(){

    if(critical condition){
        bar();  // can influence the above condition
    }
    baz(); // can influence the above condition
}

Can two threads be in bar (suppose it's called only from here)? 可以将两个线程放在bar (假设它只能从这里调用)?

What if baz can be called from another place in the code other than foo , can two threads be in it then? 如果baz可以从除foo之外的代码中的另一个地方调用,那么可以使用两个线程吗?

Can two threads be in bar (suppose it's called only from here)? 可以将两个线程放在bar中(假设它只能从这里调用)?

Yes, provided they are using different objects, or one is wait() ing. 是的,只要他们使用不同的对象,或者一个是wait() ing。

What if baz can be called from another place in the code other than foo, can two threads be in it then? 如果baz可以从除foo之外的代码中的另一个地方调用,那么可以使用两个线程吗?

Yes, placing synchronized on one method has no effect on methods which are not synchronized. 是的,在一个方法上放置synchronized会对未同步的方法没有影响。

This is an equivalent way of writing your code: 这是编写代码的等效方法:

public void foo(){
    synchronized (this) {
        if(critical condition){
            bar();  // can influence the above condition
        }
        baz(); // can influence the above condition
    }
}

Because synchronized methods actually synchronize their bodies using this as the lock object. 因为synchronized方法实际上使用this作为锁定对象来同步它们的实体。

So, can two threads be executing foo() at the same time or bar() at the same time? 那么,两个线程可以同时执行foo()还是同时执行bar() Sure, if they are executing the foo() or bar() of different objects. 当然,如果他们正在执行不同对象的foo()bar()

Also, the call to baz() is not synchronized at all, so even any two threads can run the baz() of single object at the same time, as long as at least one of them is invoking it from outside foo() . 此外,对baz()的调用根本不同步,因此即使任何两个线程也可以同时运行单个对象的baz() ,只要其中至少有一个从foo()外部调用它。

These two resources are useful for understanding what synchronization does and doesn't do in Java: 这两个资源有助于理解Java中的同步和不执行的操作:

I recommend you check those pages because there are some pieces of information that are not too obvious until you check them. 我建议您检查这些页面,因为有些信息在您检查之前不太明显。 For example: 例如:

  • Two different threads cannot execute at the same time two different synchronized methods of a single object. 两个不同的线程不能同时执行单个对象的两个不同的同步方法。
  • A single thread can be executing two different synchronized methods of the same object (called Reentrant Synchronization ) 单个线程可以执行同一对象的两个不同的同步方法(称为“ 重入同步”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM