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

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World
  • Understanding Java Signals

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Top Book Picks for Site Reliability Engineers
  • Scalability 101: How to Build, Measure, and Improve It
  • The Role of Artificial Intelligence in Climate Change Mitigation
  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

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Java Virtual Threads and Scaling
  • Java’s Next Act: Native Speed for a Cloud-Native World
  • Understanding Java Signals

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: