Java Thread sleep and join

Today, i walk you through Java Thread sleep and join methods to know how it works and how to use in practical terms. Lets begins

Java Thread Sleep

How Sleep method works
Thread.sleep() works with the thread scheduler to put the current thread in wait state for specified period of time. Thread state is changed to runnable state as the wait time is over and wait for the CPU for further execution.

Thread Sleep Example
Here is a program where Thread.sleep() is used to pause the current thread execution for 5 seconds.

Important points
a. Thread sleep always pause the current thread execution.
b. If the thread is run in a quiet system, the actual time for sleep is near to the specified sleep tim. But for a busy system it will be little bit more.
c. Thread sleep doesn’t lose any monitors or locks current thread.
d. The InterruptedException is thrown if any other thread interrupt the sleep thread.

Java Thread Join

How Join method works
Thread join() method allows one thread to wait until another thread completes its execution

Thread Join Example
Here is a simple example showing usage of Thread join methods. This program shows that our threads finish before the main thread finish.

Output of the above program is
java thread sleep, java thread join

Thread join important points
public final void join(): This method puts the current thread on wait until the joined thread finish.
public final synchronized void join(long millis): This method is used to wait for specified milliseconds.
public final synchronized void join(long millis, int nanos): This method is used to wait for thread to finish for given milliseconds plus nanoseconds.

What is the difference between join() and sleep() method in Java?
a. The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task.
b. The sleep(long millis) method causes the currently executing thread to sleep for the specified number of milliseconds.

That’s all about Java Thread sleep and join. Happy learning.

References
Pausing Execution with Sleep
Joins

Download the complete source code, click link below

JavaMultithreadExample.zip (14 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons