本文介绍了等待(长超时)和加入(长毫秒)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在线程2上由线程1调用时,wait()和join()方法都使线程1等待线程2一段时间,或者直到线程2完成.

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.

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

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

  1. 在等待(长时间超时)的情况下,线程1可以通过notify(或notifyall)运行,甚至发生超时(以先到者为准).

  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完成或发生超时(以先到者为准)时,线程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?

我认为是这些:-

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

推荐答案

正如您所说,发布"过程非常不同-如果它基于notify(),则另一个基于线程完成.它们是完全不同的呼叫,具有完全不同的目的.

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.

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

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

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

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.

这篇关于等待(长超时)和加入(长毫秒)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 05:09