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

发布于 2024-08-23 05:21:40 字数 423 浏览 1 评论 0原文

这里的第一个问题:这是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝梦月影 2024-08-30 05:21:40

不会。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 call somemethod() again on the same object, it would have to wait for the somemethod() call that created it to complete first.

甜扑 2024-08-30 05:21:40

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

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

十秒萌定你 2024-08-30 05:21:40

我猜想新线程开始与同步方法并行运行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文