gpt4 book ai didi

java - 等待()/等待(超时)/ sleep (超时)?

转载 作者:搜寻专家 更新时间:2023-11-01 04:01:37 27 4
gpt4 key购买 nike

wait() 和 wait(timeout) 之间有什么区别。无论如何 wait() 需要等待通知调用,但为什么我们有 wait(timeout)?

那么 sleep(timeout) 和 wait(timeout) 有什么区别呢?

最佳答案

如果超时后线程仍在等待,wait(timeout) 将返回。这是用于挂起通知、低功耗轮询等。Sleep(timeout) 不会在超时结束前唤醒; wait(timeout) 是 notify() 调用或超时,以先到者为准。

引用自 JavaDoc:

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object. Thread T becomes disabled for thread scheduling purposes and lies dormant until one of four things happens:

  • Some other thread invokes the notify method for this object and thread T happens to be arbitrarily chosen as the thread to be awakened.
  • Some other thread invokes the notifyAll method for this object.
  • Some other thread interrupts thread T.
  • The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into consideration and the thread simply waits until notified.

关于java - 等待()/等待(超时)/ sleep (超时)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3200402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com