Difference between wait(long timeout) and join(long millis)?

人盡茶涼 提交于 2020-01-03 14:17:39

问题


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)?

回答1:


As you say, the "release" process is quite different - in on case it's based on notify(), the other 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.



来源:https://stackoverflow.com/questions/8818721/difference-between-waitlong-timeout-and-joinlong-millis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!