Java:从同步块启动新线程时会发生什么? [英] Java: what happens when a new Thread is started from a synchronized block?
问题描述
这里的第一个问题:这是我不知道的Java中非常短却很基本的东西...
First question here: it is a very short yet fundamental thing in Java that I don't know...
在以下情况下,run()
方法是否以某种方式执行了somemethod()
确实获得的锁定?
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)
...
}
推荐答案
否. run()
在其自己的上下文中开始,即同步方式.它没有任何锁.如果这样的话,您可能会陷入死锁,或者会违反规范的规定,即在任何给定时间只有一个线程可以在对象上保持锁.
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.
如果run()
要在同一对象上再次调用somemethod()
,则必须等待创建它的somemethod()
调用首先完成.
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.
这篇关于Java:从同步块启动新线程时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!