what's the difference between yield() and sleep()?

前端 未结 4 1247
情书的邮戳
情书的邮戳 2021-01-01 00:31

I know one difference:

If we say thread.sleep(1000), that thread will sleep for 1000 milliseconds for sure, whereas with yield()

4条回答
  •  时光说笑
    2021-01-01 00:42

    It's not "for sure" -- it could even take an hour for your thread to get another chance to run, depending on the operating system's thread scheduling algorithm, and the presence of higher-priority threads.

    The only thing yield() does is say, "Okay, I'm kind of done, so feel free to end my time slice and continue executing something else." sleep, on the other hand, says "Wake me up in X milliseconds". sleep is used for waiting, the other one for giving others a chance to run. They're not alternatives.

提交回复
热议问题