Junior — Middle
What is the difference between sleep and yield functions in process or thread management?
sobes.tech AI
Answer from AI
The sleep function pauses the execution of the current thread for a specified time, releasing the processor, but the thread remains in a waiting state and is not ready to execute until the sleep time has elapsed.
The yield function voluntarily gives up the processor to other threads that are ready to run, but the current thread remains in a ready state and can be immediately resumed by the scheduler if there are no other threads or if they are not ready.
Example:
Thread.sleep(1000); // thread "sleeps" for 1 second
Thread.yield(); // thread offers the scheduler to switch to another thread
Thus, sleep is used for pausing, and yield is used for voluntary relinquishing of the processor without pausing.