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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • DZone's Article Submission Guidelines
  • The End of “Good Enough Agile”
  • MCP Servers: The Technical Debt That Is Coming
  • Event Driven Architecture (EDA) - Optimizer or Complicator
  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 (9)
Comment
Save
Tweet
Share
15.0K 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

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!