Difference between wait() and sleep()

前端 未结 30 3194
無奈伤痛
無奈伤痛 2020-11-22 00:24

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in runni

30条回答
  •  故里飘歌
    2020-11-22 00:40

    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.

    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.

    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.

提交回复
热议问题