Problem:

How to Java Thread join to do simple synchronization of threads? In this post we show an example where one thread waits for another to clean up after it. Read on!

Solution:

When a couple of threads have to do work sequentially we can guarantee their order in a few ways. One way could be to use Single Thread Executor that can serialize threads. In the below example we’re going to show how to do that using Thread.join() method, which is sufficient for simple cases.

The Thread.join() method when called from one thread, stops it, and waits for the other thread to die. In the example we have a BusyJob thread that we want to run first and a JobCleaner thread that we want to run after the busy job has finished. In the main thread we start JobCleaner thread, which will start BusyJob thread – both threads could be started from the main thread, but we implemented it this way. Also in main thread we are waiting for the cleaner to finish and then we end the program.

void join(long millis) It waits for given number of milliseconds for this thread to die.

void join(long millis, int nanos) It waits for given number of milliseconds plus nanoseconds for this thread to die.

And here’s the result of running the above example:

Starting the cleaner.
main is waiting for the cleaner to finish
Cleaner is waiting on a busy job...
Started BusyJob...
Busy job done.
Cleaning up after job: BusyJob
Cleaning done.
End of main thread!

As you can see all threads have executed in order as expected. This method of serialization is fine for simple cases like this one, but for more threads it may get complicated very fast and then better use Single Thread Executor.