Java wait() 和 sleep() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1036754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between wait() and sleep()
提问by Geek
What is the difference between a wait()
and sleep()
in Threads?
await()
和sleep()
in Threads 有什么区别?
Is my understanding that a wait()
-ing Thread is still in running mode and uses CPU cycles but a sleep()
-ing does not consume any CPU cycles correct?
我的理解是wait()
-ing 线程仍处于运行模式并使用 CPU 周期,但sleep()
-ing 不消耗任何 CPU 周期是否正确?
Why do we have bothwait()
and sleep()
: how does their implementation vary at a lower level?
为什么我们都wait()
和sleep()
:如何实现他们在一个较低的水平有什么不同?
采纳答案by oxbow_lakes
A wait
can be "woken up" by another thread calling notify
on the monitor which is being waited on whereas a sleep
cannot. Also a wait
(and notify
) must happen in a block synchronized
on the monitor object whereas sleep
does not:
Await
可以被另一个线程调用notify
正在等待的监视器上“唤醒”,而 asleep
不能。此外,wait
(and notify
) 必须出现在synchronized
监视器对象的块中,而sleep
不会:
Object mon = ...;
synchronized (mon) {
mon.wait();
}
At this point the currently executing thread waits and releases the monitor. Another thread may do
此时当前正在执行的线程等待并释放监视器。另一个线程可能会做
synchronized (mon) { mon.notify(); }
(on the same mon
object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
(在同一个mon
对象上)并且第一个线程(假设它是在监视器上等待的唯一线程)将被唤醒。
You can also call notifyAll
if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait
is in a synchronized
block) and carry on – the others will then be blocked until they can acquire the monitor's lock.
notifyAll
如果有多个线程在监视器上等待,您也可以调用- 这将唤醒所有线程。然而,只有一个线程能够获取监视器(记住它wait
在一个synchronized
块中)并继续执行——其他线程将被阻塞,直到它们能够获取监视器的锁。
Another point is that you call wait
on Object
itself (i.e. you wait on an object's monitor) whereas you call sleep
on Thread
.
另一点是,你叫wait
上Object
本身(即您等待对象的监视器上),而你打电话sleep
的Thread
。
Yet another point is that you can get spurious wakeupsfrom wait
(i.e. the thread which is waiting resumes for no apparent reason). You should always wait
whilst spinning on some conditionas follows:
还有一点是,您可以从(即等待恢复的线程无缘无故地恢复)获得虚假wait
唤醒。您应该始终wait
在某些条件下旋转,如下所示:
synchronized {
while (!condition) { mon.wait(); }
}
回答by Ratnesh Maurya
In simple words, wait is wait Until some other thread invokes you whereas sleep is "dont execute next statement" for some specified period of time.
简单来说,wait 就是等待其他线程调用您,而 sleep 是在某个指定的时间段内“不执行下一条语句”。
Moreover sleep is static method in Thread class and it operates on thread, whereas wait() is in Object class and called on an object.
此外 sleep 是 Thread 类中的静态方法,它对线程进行操作,而 wait() 在 Object 类中并在对象上调用。
Another point, when you call wait on some object, the thread involved synchronize the object and then waits. :)
还有一点,当你对某个对象调用 wait 时,所涉及的线程会同步该对象然后等待。:)
回答by Roee Adler
wait
and sleep
methods are very different:
wait
和sleep
方法非常不同:
sleep
has no way of "waking-up",- whereas
wait
has a way of "waking-up" during the wait period, by another thread callingnotify
ornotifyAll
.
Come to think about it, the names are confusing in that respect; however sleep
is a standard name and wait
is like the WaitForSingleObject
or WaitForMultipleObjects
in the Win API.
想想看,这些名字在这方面令人困惑;然而sleep
是一个标准名称,wait
类似于Win API 中的WaitForSingleObject
或WaitForMultipleObjects
。
回答by Itay Maman
Wait and sleep are two different things:
等待和睡眠是两件不同的事情:
- In
sleep()
the thread stops working for the specified duration. - In
wait()
the thread stops working until the object being waited-on is notified, generally by other threads.
- 在
sleep()
线程停止工作指定的持续时间。 - 在
wait()
线程停止工作,直到被等待的对象被通知,通常由其他线程通知。
回答by Justin
You are correct - Sleep() causes that thread to "sleep" and the CPU will go off and process other threads (otherwise known as context switching) wheras I believe Wait keeps the CPU processing the current thread.
你是对的 - Sleep() 导致该线程“休眠”,CPU 将关闭并处理其他线程(也称为上下文切换),而我相信 Wait 会保持 CPU 处理当前线程。
We have both because although it may seem sensible to let other people use the CPU while you're not using it, actualy there is an overhead to context switching - depending on how long the sleep is for, it can be more expensive in CPU cycles to switch threads than it is to simply have your thread doing nothing for a few ms.
我们两者都有,因为尽管在您不使用 CPU 时让其他人使用它似乎是明智的,但实际上上下文切换会产生开销 - 取决于睡眠的时间长短,CPU 周期可能会更昂贵切换线程而不是简单地让您的线程在几毫秒内什么都不做。
Also note that sleep forces a context switch.
另请注意,睡眠会强制进行上下文切换。
Also - in general it's not possible to control context switching - during the Wait the OS may (and will for longer waits) choose to process other threads.
此外 - 通常无法控制上下文切换 - 在等待期间,操作系统可能(并将等待更长的时间)选择处理其他线程。
回答by Robert Munteanu
One key difference not yet mentioned is that while sleeping a Thread does notrelease the locks it holds, while waiting releases the lock on the object that wait()
is called on.
尚未提及的一个关键区别是,当一个线程休眠时,它不会释放它持有的锁,而在等待时释放wait()
被调用对象上的锁。
synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}
synchronized(LOCK) {
LOCK.wait(); // LOCK is not held
}
回答by E-rich
I found this posthelpful. It puts the difference between Thread.sleep()
, Thread.yield()
, and Object.wait()
in human terms. To quote:
我发现这篇文章很有帮助。它把Thread.sleep()
, Thread.yield()
, 和之间的区别放在了Object.wait()
人类术语中。报价:
It all eventually makes its way down to the OS's scheduler, which hands out timeslices to processes and threads.
sleep(n)
says “I'm done with my timeslice, and please don't give me another one for at least n milliseconds.”The OS doesn't even try to schedule the sleeping thread until requested time has passed.
yield()
says “I'm done with my timeslice, but I still have work to do.”The OS is free to immediately give the thread another timeslice, or to give some other thread or process the CPU the yielding thread just gave up.
wait()
says “I'm done with my timeslice. Don't give me another timeslice until someone calls notify().”As withsleep()
, the OS won't even try to schedule your task unless someone callsnotify()
(or one of a few other wakeup scenarios occurs).Threads also lose the remainder of their timeslice when they perform blocking IO and under a few other circumstances. If a thread works through the entire timeslice, the OS forcibly takes control roughly as if
yield()
had been called, so that other processes can run.You rarely need
yield()
, but if you have a compute-heavy app with logical task boundaries, inserting ayield()
mightimprove system responsiveness (at the expense of time — context switches, even just to the OS and back, aren't free). Measure and test against goals you care about, as always.
这一切最终都归结为操作系统的调度程序,它将时间片分发给进程和线程。
sleep(n)
说“我已经完成了我的时间片,请在至少 n 毫秒内不要再给我一个。” 在请求的时间过去之前,操作系统甚至不会尝试安排睡眠线程。
yield()
说“我的时间片已经完成了,但我还有工作要做。” 操作系统可以自由地立即给线程另一个时间片,或者给其他线程或处理 CPU 刚刚放弃的屈服线程。
wait()
说“我已经完成了我的时间片。在有人调用 notify() 之前不要给我另一个时间片。” 与 一样sleep()
,操作系统甚至不会尝试安排您的任务,除非有人打电话notify()
(或发生其他一些唤醒场景之一)。线程在执行阻塞 IO 和其他一些情况时也会丢失其剩余的时间片。如果一个线程在整个时间片上工作,操作系统会像
yield()
被调用一样强制控制,以便其他进程可以运行。你很少需要
yield()
,但是如果你有逻辑的任务边界的计算,重应用,插入yield()
可能会提高系统的响应速度(时间为代价-上下文切换,甚至只是在OS和背部,是不是免费的)。一如既往地针对您关心的目标进行衡量和测试。
回答by om singh
source : http://www.jguru.com/faq/view.jsp?EID=47127
来源:http: //www.jguru.com/faq/view.jsp?EID=47127
Thread.sleep()
sends the current thread into the "Not Runnable"state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread callst.interrupt()
it will wake up the sleeping thread.Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call
t.sleep()
where t is a different thread; even then, it is the current thread that will sleep, not the t thread.
t.suspend()
is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.
object.wait()
sends the current thread into the "Not Runnable"state, likesleep()
, but with a twist. Wait is called on an object, not a thread; we call this object the "lock object." Beforelock.wait()
is called, the current thread must synchronize on the lock object;wait()
then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and calllock.notify()
. This wakes up the original, waiting thread. Basically,wait()
/notify()
is likesleep()
/interrupt()
, only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
Thread.sleep()
将当前线程发送到“不可运行”状态一段时间。线程保持它获得的监视器——即,如果线程当前处于同步块或方法中,则没有其他线程可以进入该块或方法。如果另一个线程调用t.interrupt()
它会唤醒休眠线程。请注意, sleep 是一种静态方法,这意味着它始终影响当前线程(正在执行 sleep 方法的线程)。一个常见的错误是调用
t.sleep()
where t 是不同的线程;即便如此,休眠的是当前线程,而不是 t 线程。
t.suspend()
已弃用。使用它可以暂停当前线程以外的线程。挂起的线程保留其所有监视器,并且由于此状态不可中断,因此容易发生死锁。
object.wait()
将当前线程发送到“不可运行”状态,如sleep()
,但有一些变化。Wait 是在一个对象上调用的,而不是一个线程;我们称这个对象为“锁对象”。在lock.wait()
被调用之前,当前线程必须在锁对象上同步;wait()
然后释放此锁,并将线程添加到与该锁关联的“等待列表”中。稍后,另一个线程可以同步同一个锁对象并调用lock.notify()
. 这会唤醒原始的等待线程。基本上,wait()
/notify()
就像sleep()
/interrupt()
,只有活动线程不需要指向睡眠线程的直接指针,而只需要指向共享锁对象。
回答by pavan
Lets assume you are hearing songs.
假设您正在听歌曲。
As long as the current song is running, the next song wont play, i.e Sleep() called by next song
只要当前歌曲在运行,下一首歌曲就不会播放,即下一首歌曲调用的Sleep()
If you finish the song it will stop and until you select play button(notify()) it wont play, i.e wait() called by current song.
如果你完成这首歌,它会停止,直到你选择播放按钮(notify()),它才会播放,即当前歌曲调用的 wait()。
In this both cases songs going to Wait states.
在这两种情况下,歌曲都会进入等待状态。
回答by Vikas Gupta
This is a very simple question, because both these methods have a totally different use.
这是一个非常简单的问题,因为这两种方法的用途完全不同。
The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.
主要区别是等待释放锁或监视器,而睡眠在等待时不会释放任何锁或监视器。Wait 用于线程间通信,而 sleep 用于在执行时引入暂停。
This was just a clear and basic explanation, if you want more than that then continue reading.
这只是一个清晰而基本的解释,如果您想要更多,请继续阅读。
In case of wait()
method thread goes in waiting state and it won't come back automatically until we call the notify()
method (or notifyAll()
if you have more then one thread in waiting state and you want to wake all of those thread). And you need synchronized or object lock or class lock to access the wait()
or notify()
or notifyAll()
methods. And one more thing, the wait()
method is used for inter-thread communication because if a thread goes in waiting state you'll need another thread to wake that thread.
如果wait()
方法线程进入等待状态并且在我们调用该notify()
方法之前它不会自动返回(或者notifyAll()
如果您有多个线程处于等待状态并且您想唤醒所有这些线程)。并且您需要同步或对象锁或类锁来访问wait()
或notify()
或notifyAll()
方法。还有一件事,该wait()
方法用于线程间通信,因为如果一个线程进入等待状态,您将需要另一个线程来唤醒该线程。
But in case of sleep()
this is a method which is used to hold the process for few seconds or the time you wanted. Because you don't need to provoke any notify()
or notifyAll()
method to get that thread back. Or you don't need any other thread to call back that thread. Like if you want something should happen after few seconds like in a game after user's turn you want the user to wait until the computer plays then you can mention the sleep()
method.
但在sleep()
这种情况下,这是一种用于将过程保持几秒钟或您想要的时间的方法。因为您不需要激发任何notify()
或notifyAll()
方法来取回该线程。或者您不需要任何其他线程来回调该线程。就像如果您希望在几秒钟后发生某些事情,例如在轮到用户之后的游戏中,您希望用户等到计算机播放,然后您可以提及该sleep()
方法。
And one more important difference which is asked often in interviews: sleep()
belongs to Thread
class and wait()
belongs to Object
class.
还有一个在面试中经常被问到的重要区别:sleep()
属于Thread
阶级和wait()
属于Object
阶级。
These are all the differences between sleep()
and wait()
.
这些都是sleep()
和之间的区别wait()
。
And there is a similarity between both methods: they both are checked statement so you need try catch or throws to access these methods.
这两种方法之间有一个相似之处:它们都是检查语句,因此您需要 try catch 或 throws 来访问这些方法。
I hope this will help you.
我希望这能帮到您。