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

心不动则不痛 提交于 2019-12-12 10:39:41

问题


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.



来源:https://stackoverflow.com/questions/2340114/java-what-happens-when-a-new-thread-is-started-from-a-synchronized-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!