Java Multithreading, Concurrency, and Parallelism — Part 5
NO Guarantee on the order of execution of threads and the join()
method
In part-4, we have seen that we can create multiple threads giving the same Runnable. Here we look at the same example and understand the order of their execution.
The above code creates a single Runnable
instance and three Thread
instances. All three Thread
instances get the same Runnable instance, and each thread is given a unique name: t1
, t2
, and t3
. Finally, all three threads are started by invoking start()
on those three instances.
Run this program multiple times, and you won’t see the same output every time. Let me rephrase. You may or may not get the same output every time you run the program. One thumb rule about threads in Java is that the order of their execution is NOT guaranteed.
Here are the few points that are to be noted.
- Each thread will start and complete. Once a thread has been started, it can never be started again. We will get
IllegalThreadStateException
if we callstart()
again on the same thread instance. - Though we started
t1
first, followed byt2
andt3
, there is no guarantee thatt1
will ever run first. It is all up to the JVM…