Junior — Middle
Чем отличаются функции sleep, wait и yield в контексте многопоточности?
sobes.tech AI
Answer from AI
In the context of multithreading in Java, the functions sleep, wait, and yield have different purposes:
-
sleep(long millis):
- Pauses the execution of the current thread for the specified time.
- Does not release the monitor (lock) if it is held.
- Used for delays.
-
wait():
- Causes the current thread to wait on an object, releasing the monitor of that object and entering the waiting state.
- The thread will wait until another thread calls
notify()ornotifyAll()on the same object. - Used for inter-thread communication and synchronization.
-
yield():
- Suggests to the thread scheduler to give other threads of the same priority a chance to run.
- The thread does not block or enter a waiting state; it simply pauses temporarily.
- Used to improve scheduling but does not guarantee a switch.
Example:
Thread.sleep(1000); // pause for 1 second
synchronized(obj) {
obj.wait(); // wait for notification
}
Thread.yield(); // suggest scheduler to switch