πŸŽ‰ Special Offer !    Code: GET300OFF    Flat β‚Ή300 OFF on every Java Course
Grab Deal πŸš€

sleep() VS yield() VS join()  


Difference between sleep(), yield() and join()
  • sleep():
    • Pauses the current thread for a specified time without releasing locks.
  • yield():
    • Temporarily pauses the current thread to give other threads of equal priority a chance to execute.
  • join():
    • Makes the current thread wait until the specified thread completes its execution.
  • The following table highlights the key differences between 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.