等待(长超时)和加入(长毫秒)之间的区别?

发布于 2024-12-26 18:47:29 字数 527 浏览 3 评论 0原文

当线程 1 在线程 2 上调用 wait() 和 join() 方法时,线程 1 会等待线程 2,一段时间或直到线程 2 完成。

如果我们使用这些方法的重载版本,即 wait(long timeout) 和 join(long millis),那么

  1. 在 wait(long timeout) 的情况下,thread-1 将通过 notify(或 notifyall)或即使发生超时(以先到者为准)。

  2. 如果是 join(long millis),当 thread-2 完成或超时(以先到者为准)时,thread-2 将变为可运行状态。

那么这两种实现方式有什么区别呢?

我想到的一些是:-

  1. 对于 wait(),我们需要锁定我们正在等待的对象。对于 join() 来说,这些不是必需的。
  2. 执行 wait() 后,线程会删除它所获得的锁,并在再次运行时重新获得锁。但是加入呢?如果这是从同步块(或方法)执行的,线程在执行 join 后是否会删除锁?

Both of wait() and join() methods when called by thread-1 on thread-2 makes thread-1 wait for the thread-2, either for sometime or till thread-2 completes.

If we are using the overloaded versions of these methods i.e. wait(long timeout) and join(long millis), then

  1. In case of wait(long timeout), thread-1 will become runnable either by notify (or notifyall) or even timeout occurs (whichever is first).

  2. In case of join(long millis), thread-2 will become runnable either when thread-2 completes or timeout occurs (whichever is first).

So then what is the difference between these two implementations?

Some that I thought are these :-

  1. For wait(), we need to have the lock on the object we are waiting on. For join() these are not necessary.
  2. After executing wait(), the thread removes lock it obtained and re-gains the lock once it becomes running again. But what about join? Does a thread removes a lock after executing join if this was executed from a synchronized block (or method)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

酷到爆炸 2025-01-02 18:47:29

正如您所说,“发布”过程完全不同 - 在一种情况下(等待)它基于 notify(),另一种情况(加入)它基于线程完成。它们是完全不同的调用,具有完全不同的目的。

事实上,有明确的警告Thread监视器上调用wait()(尽管我无法立即找到这些警告),如内部 Java 代码为它们获取锁(并使用 wait/notify 本身)。

但不,如果当前正在执行的线程拥有监视器,则在 Thread 上调用 join() 不会释放监视器。

基本上,你不应该认为它们是相似的——一个是等待线程终止;另一个是等待线程终止。二是等待合作协调。

As you say, the "release" process is quite different - in one case (wait) it's based on notify(), the other (join) it's based on the thread completing. They're entirely different calls which serve entirely different purposes.

In fact, there are explicit warnings not to call wait() on Thread monitors (although I can't immediately find those warnings), as internal Java code acquires the locks for them (and uses wait/notify itself).

But no, calling join() on Thread doesn't release the monitor if the currently executing thread owns it.

Basically, you shouldn't think of them as similar at all - one is for waiting for a thread to terminate; the other is for waiting for co-operative coordination.

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