What is difference between sleep() method and yield() method of multi threading?

前端 未结 12 1791
野的像风
野的像风 2020-12-22 17:02

As currently executing thread while it encounters the call sleep() then thread moves immediately into sleeping stat. Whereas for yield() thread moves into runnable

12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 17:19

    We can prevent a thread from execution by using any of the 3 methods of Thread class:

    1. yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

    2. join() If any executing thread t1 calls join() on t2 (i.e. t2.join()) immediately t1 will enter into waiting state until t2 completes its execution.

    3. sleep() Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).

提交回复
热议问题