sleep() VS yield() VS join()
sleep(), yield() and join()
sleep():
yield():
join():
sleep(), yield() and join() methods in Java:
| Property | sleep() | yield() | join() |
|---|---|---|---|
| Purpose | Pauses the execution of the current thread for a specified duration, allowing other threads to run during this time. | Temporarily pauses the current thread and gives a chance for other threads of equal priority to execute. | Causes the current thread to wait until the specified thread completes its execution before proceeding. |
| Examples | Timers, presentations (PPT auto-change), blinking indicators. | Shopping tasks, CPU-sharing scenarios. | License department processing: waiting for one task to finish before starting the next. |
| How the Thread Invokes Again? | Automatically after the specified sleep duration ends or if the thread is interrupted. | Automatically resumes after other threads of equal priority get execution or the scheduler decides. | Resumes execution after the target thread completes its task or after a specified waiting time if a timed join is used. |
| Methods |
β’ sleep(long ms)β’ sleep(long ms, int ns)
|
yield() |
β’ join()β’ join(long ms) β’ join(long ms, int ns)
|
| Method Overloaded? | Yes | No | Yes |
| Exception | Throws InterruptedException |
None | Throws InterruptedException |
| Is Method Final? | Yes | No | Yes |
| Is Method Static? | Yes | Yes | No |
| Is Method Native? |
β’ sleep(long ms) β nativeβ’ sleep(long ms, int ns) β non-native
|
Yes | No |
| Thread State Transition | Running β Timed Waiting | Running β Runnable | Running β Waiting |
| Guarantee | Guarantees thread pauses for the specified time. | No guarantee; thread may continue or other threads may run. | Guarantees current thread waits until the target thread completes. |
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.