Multithreading in Java

Upanshu Chaudhary
4 min readJun 11, 2022

--

Every programmer comes across Multithreading and for some reason, it has been considered hard to understand. Well, it’s not. In this blog, we will go through some basics of multithreading and in the process will try to understand why it is such an important topic in software development.

A program can have multiple processes and Multithreading allows us to run these multiple processing units concurrently. Our programs by default run on a Single thread also known as the main thread. Multithreading is useful because:

  • It helps us to perform multitasking and make our application more efficient by effectively using CPU resources.
  • This also takes a load off the main thread and increases application performance.
  • Different threads run concurrently so they do not interfere with each other’s processes. If an exception occurs on a thread, it won’t affect the working of others.
  • Decreased maintenance cost.

We can create threads in java by extending the java.lang.Thread class or by implementing the java.lang.Runnable interface. Both the implementation overrides the run() method to do so. Both the implementations can be used according to the use case of the class.

Creating Thread Using Thread Class

@Component
public class MultiThreadingExample extends Thread{
private final static Logger log = LoggerFactory.getLogger(MultiThreadingExample.class);

@Override
public void run() {
log.info("This class extends Thread class
for multithreading");
}
}

While extending Thread class the important thing to keep in mind is that when threads will create new instance of the class on which it is called. There is no instance sharing.

Creating Thread Using Runnable Interface

@Component
public class MultiThreadingByRunnable implements Runnable{
private final static Logger log = LoggerFactory.getLogger(MultiThreadingByRunnable.class);

@Override
public void run() {
log.info("This class implements the runnable interface");
}
}

If you will drill down and explore the Thread class you will be able to see that internally it implements the Runnable interface:

Result:

@SpringBootApplication
public class JavaLearningApplication {
public static void main(String[] args) {
SpringApplication.run(JavaLearningApplication.class, args);

MultiThreadingExample multiThreadingExample =
new MultiThreadingExample();

multiThreadingExample.start();
Thread runnableImpl = new Thread(new MultiThreadingByRunnable());
runnableImpl.start();
}

Which method to use?

  • It is preferred to use Runnable interface instead of the extending the Thread class.
  • If we extend the thread class for creating a thread we cannot extend any other class because java does not support multiple inheritances. We can avoid this limitation by using the Runnable interface, this will allow us to extend some other class.
  • Extending Thread class leads to tight coupling where as implementing Runnable keeps things loosely coupled.
  • While using Runnable we are not specialising the behaviour of thread but instead are just giving it something to run.
  • By implementing Runnable multiple threads can share an instance as Runnable is task based, it does not create a new thread. To create a new thread the class instance need to be passed in Thread() class. So Runnable can also just be used for overriding the run() method without creating a new Thread.
RunnableClass runnableInstance = new RunnableClass();Thread t1 = new Thread(runnableInstance);   //instance sharing
Thread t2 = new Thread(runnableInstance); //instance sharing

Java Thread Life Cycle

Now we know how to create threads but to increase our understanding let’s look at what actually is the lifecycle of this thread. Thread can be in one of these states at any point in time:

  1. New: When the thread object is created or initialized. This is the birth of thread. Thread instance is very excited but doesn’t know what awaits him ahead.
  2. Runnable: In this state the thread is ready to run, all the teenage energy is pent up inside and it's just waiting for its turn to run.
  3. Running: This is the state in which the thread is running and executing the process. The thread is now an adult, it does work efficiently.
  4. Waiting: This is the state when the thread is inactive due to some resource blocking etc. I don't have a relatable situation for this one.
  5. Terminated: This is the end of the thread lifecycle, here it completes the process and dies. It will be remembered for its contributions by us but not by the Java memory.

This blog was just a tip of the ice berg and an introduction to Multithreading. Java is vast and so is the concept of Multithreading. Apart from the mentioned methods, Java provides a Multithreading API known as Java Executor Framework which creates and manages threads efficiently and is heavily used in Multithreaded Applications. I will try to cover that in the future blogs, until then I hope this helped and let me know in the comments if you have more information to share on the topic!

My Github profile.

You can checkout my other blogs here.

--

--

Upanshu Chaudhary
Upanshu Chaudhary

Written by Upanshu Chaudhary

Graduate Teaching Assistant and Student at Oregon State University. Open-source enthusiast. Probably busy reading code on a Random github profile.

No responses yet