~Onlooker 2009-06-24 06:48 采纳率: 0%
浏览 1235
已采纳

等待与睡眠之间的区别

What is the difference between a wait() and 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?

Why do we have both wait() and sleep(): how does their implementation vary at a lower level?

转载于:https://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep

  • 写回答

30条回答 默认 最新

  • from.. 2009-06-24 06:50
    关注

    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:

    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.

    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.

    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.

    Yet another point is that you can get spurious wakeups from wait (i.e. the thread which is waiting resumes for no apparent reason). You should always wait whilst spinning on some condition as follows:

    synchronized {
        while (!condition) { mon.wait(); }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题