等待(长超时)和加入(长毫秒)之间的区别?
当线程 1 在线程 2 上调用 wait() 和 join() 方法时,线程 1 会等待线程 2,一段时间或直到线程 2 完成。
如果我们使用这些方法的重载版本,即 wait(long timeout) 和 join(long millis),那么
在 wait(long timeout) 的情况下,thread-1 将通过 notify(或 notifyall)或即使发生超时(以先到者为准)。
如果是 join(long millis),当 thread-2 完成或超时(以先到者为准)时,thread-2 将变为可运行状态。
那么这两种实现方式有什么区别呢?
我想到的一些是:-
- 对于 wait(),我们需要锁定我们正在等待的对象。对于 join() 来说,这些不是必需的。
- 执行 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
In case of wait(long timeout), thread-1 will become runnable either by notify (or notifyall) or even timeout occurs (whichever is first).
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 :-
- For wait(), we need to have the lock on the object we are waiting on. For join() these are not necessary.
- 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所说,“发布”过程完全不同 - 在一种情况下(等待)它基于
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()
onThread
monitors (although I can't immediately find those warnings), as internal Java code acquires the locks for them (and useswait
/notify
itself).But no, calling
join()
onThread
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.