简体   繁体   English

Java:从同步块启动新线程时会发生什么?

[英]Java: what happens when a new Thread is started from a synchronized block?

First question here: it is a very short yet fundamental thing in Java that I don't know... 这里的第一个问题:在Java中它是一个非常短暂但基本的东西,我不知道......

In the following case, is the run() method somehow executed with the lock that somemethod() did acquire? 在下面的例子中, run()方法somemethod()确实获取的锁以某种方式执行的?

public synchronized void somemethod() {
    Thread t = new Thread( new Runnable() {
       void run() {
           ...          <-- is a lock held here ?
       }
    }
    t.start();
    ... 
    (lengthy stuff performed here, keeping the lock held)
    ...
}

No. run() starts in its own context, synchronization-wise. 编号run()从它自己的上下文开始,同步。 It doesn't hold any locks. 它没有任何锁定。 If it did, you would either have a deadlock or it would violate the specs that state that only one thread may hold the lock on an object at any given time. 如果确实如此,您将遇到死锁或者违反规范,该规范声明在任何给定时间只有一个线程可以锁定对象。

If run() was to call somemethod() again on the same object, it would have to wait for the somemethod() call that created it to complete first. 如果run()要在同一个对象上再次调用somemethod() ,则必须等待创建它的somemethod()调用首先完成。

不,只有原始线程具有锁定(因为实际上只有一个线程可以持有锁)。

I'd guess that the new thread starts running in parallel to the synchronized method. 我猜这个新线程开始与synchronized方法并行运行。

someMethod() still holds its own lock which only prevents this method from being invoked simultaneously against this instance of the object. someMethod()仍然拥有自己的锁,只能防止对该对象实例同时调用此方法。

The thread does not inherit the lock, and will only be inhibited by the lock if the thread tries to call someMethod() against the object which created it if someMethod() is currently executing for that object. 线程不会继承锁,只有当线程尝试对创建它的对象调用someMethod()时才会被锁禁止,如果someMethod()当前正在为该对象执行的话。

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

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