Sitemap
2 min readMar 11, 2025

--

Multithreading in Java

What is multithreading?

Multithreading is a programming technique that allows multiple parts of a program (threads) to run concurrently, improving performance and efficiency. It makes better use of CPU cores by allowing a single process to carry out several tasks concurrently.

So now what is Thread?

A lightweight process that runs independently like simply it is the smallest unit of execution within a process.

How to create a Thread?

Generally, In java Thread can be created in three ways.

  1. Extending Thread class
  2. Implementing Runnable Interface
  3. Implementing Callable Interface

There are other ExecutorFrameworks which we will discuss later.

Get SaiDurga Devireddy’s stories in your inbox

Join Medium for free to get updates from this writer.

Extending Thread class

Creating Thread by extending Thread class

Here we don’t have control of the threads we are creating and we cant extend more than one class.

Implementing Runnable Interface

Press enter or click to view image in full size
Creating Thread by Implementing Runnable Interface

Implementing Callable Interface

Press enter or click to view image in full size
Creating Thread By implementing Callable Interface

We use callable interface when we would like to return any value after the thread execution completed.

In the above example, we used ExecutorService through which we can have singleThreadExecutor() and executor.submit() allows us to call the abstract method call() for callable interface and this is where we write the task the thread needs to implement.

Future.get() waits until the thread execution completed which is a blocking call and return the result.

For executors, we have to manually shutdown() the service( will discuss this more in the next posts).

--

--

SaiDurga Devireddy
SaiDurga Devireddy

Written by SaiDurga Devireddy

I aim to share insights, best practices, and lessons learned from my experience with Java, Spring Boot, Microservices, AWS. Let’s learn and grow together!