Java: what happens when a new Thread is started fr

2019-06-20 14:08发布

问题:

First question here: it is a very short yet fundamental thing in Java that I don't know...

In the following case, is the run() method somehow executed with the lock that somemethod() did acquire?

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)
    ...
}

回答1:

No. run() starts in its own context, synchronization-wise. 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.



回答2:

No, only the original thread has the lock (because only one thread can hold a lock actually).



回答3:

I'd guess that the new thread starts running in parallel to the synchronized method.

someMethod() still holds its own lock which only prevents this method from being invoked simultaneously against this instance of the object.

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.