DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Trending

  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  • Smart Deployment Strategies for Modern Applications
  • S3 Vectors: How to Build a RAG Without a Vector Database
  • From APIs to Actions: Rethinking Back-End Design for Agents
  1. DZone
  2. Coding
  3. Java
  4. Multithreading in Java

Multithreading in Java

Every programmer comes across Multithreading and for some reason, it has been considered hard to understand. Well, it's not.

By 
Upanshu Chaudhary user avatar
Upanshu Chaudhary
·
Jun. 12, 21 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
15.4K Views

Join the DZone community and get the full member experience.

Join For Free

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

Java
 
@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");
    }

}


Creating Thread Using Runnable Interface

Java
 
@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:

Java
 
@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();
	}

}


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.

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 is all for this blog. Hope this helped you all with some basics about Multithreading in Java. We will try to cover more topics related to this in the future.

Here is the link for my other blogs.

Here is the Github link for the example.

Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Detecting Bugs and Vulnerabilities in Java With SonarQube
  • Introduction to Tactical DDD With Java: Steps to Build Semantic Code
  • AI Agents in Java: Architecting Intelligent Health Data Systems
  • OpenAPI From Code With Spring and Java: A Recipe for Your CI

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook