Java Multithreading, Concurrency, and Parallelism — Part 5

KRISHNA KISHORE V
5 min readJul 21, 2021

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.

  1. Each thread will start and complete. Once a thread has been started, it can never be started again. We will get IllegalThreadStateException if we call start() again on the same thread instance.
  2. Though we started t1 first, followed by t2 and t3, there is no guarantee that t1 will ever run first. It is all up to the JVM…

--

--

KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer