Java:当从同步块启动新线程时会发生什么?
这里的第一个问题:这是 Java 中一个非常简短但基本的东西,我不知道......
在下面的情况下,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)
...
}
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)
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会。
run()
在其自己的上下文中启动(同步)。它不持有任何锁。如果确实如此,您要么会遇到死锁,要么会违反规定在任何给定时间只有一个线程可以持有对象锁的规范。如果
run()
要对同一对象再次调用somemethod()
,则必须等待创建的somemethod()
调用首先要完成它。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 callsomemethod()
again on the same object, it would have to wait for thesomemethod()
call that created it to complete first.不,只有原始线程拥有锁(因为实际上只有一个线程可以持有锁)。
No, only the original thread has the lock (because only one thread can hold a lock actually).
我猜想新线程开始与同步方法并行运行。
someMethod() 仍然持有自己的锁,这只会阻止针对对象的此实例同时调用此方法。
该线程不会继承锁,并且仅当线程尝试对创建它的对象调用 someMethod()(如果当前正在为该对象执行 someMethod())时,该线程才会被锁禁止。
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.