Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding Multithreading in Java with Examples

Understanding Multithreading in Java with Examples

13 Sep 2024
Intermediate
1.05K Views
9 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

Multithreading in Java

Do you know that you can execute more than one thread at once in Java? Multithreading in Java! This is the process used. Execution of two or more threads at the same time within a single program is allowed by Multithreading in Java.

We will try to understand in detail what Java Multithreading is in this Java Tutorial. We will also go through other concepts related to it. To learn more about various concepts of Java Programming, enroll in a Java Full Stack Developer Course Program.

Read More: Best Java Developer Roadmap 2024

Before digging deep into multithreading, it would be good to know about threads and learn about multitasking.

What is Multitasking?

A computer's capacity to implement several tasks at the same time is referred to as multitasking. Broadly speaking, it comes in two varieties which are process-oriented or Multiprocessing and thread-oriented or Multithreading.

Types of Multitasking

Types of Multitasking

1. Multiprocessing in Java

Multiprocessing means that a system has a capacity that exceeds a processor as well as can also execute various processes at the same time. In Java, this is done by creating several parallel running processes. Each process is executed in its own JVM instance.

2. Multithreading in Java

With Java's multithreading, programs may have multiple threads running concurrently. Threads share the same memory space and can access the same resources; this is more efficient than process-based multitasking.

What is a Thread in Java?

In Java, there is a concept of a thread which means a lightweight process with its own call stack. However, it can possibly share the same resources and data with other threads. In Java, multithreading is supported natively so you just simply have to build synchronized applications.

Example of Threads in Java:

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running.");
    }
    
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Hereby, it is explained that a `MyThread` thread instance is created using an extended `Thread` class. The 'run' method is called once the thread has started running by invoking the 'start' method.

Output

Thread is running.

Lifecycle of a Thread in Java

A thread in Java goes through several states during its lifecycle. These states are as follows:

Lifecycle of a Thread in Java

1. New

Whenever a thread is made, it stays in the "new" condition; in this condition, the thread isn’t qualified to run yet.

2. Runnable

When a thread object's start() method is called, the thread will start to be scheduled for running. It is ready to run and waiting for the operating system to allocate CPU time.

3. Running

When the thread scheduler picks a thread from the runnable pool, it enters the "running" state and executes its task.

4. Waiting

If it wants another thread to do something particular, a thread goes into the "waiting" state. This can occur through various mechanisms, such as wait(), sleep(), or waiting for I/O operations.

5. Dead

The run method completion or an exception being thrown brings the thread into the "dead" state. After entering this state, the thread cannot be restarted.

Read More: Java Multithreading Interview Questions and Answers 2024

Now that we have covered the important requirements the main topic is going to be Multithreading in Java.

What is Multithreading in Java?

Multithreading in Java is the execution of multiple threads within a single application at the same time. Each thread runs in parallel, performing different tasks. This capability is essential for developing high-performance applications, such as servers, which need to handle multiple client requests simultaneously.

Methods of Multithreading in Java

Java provides several methods to implement multithreading, including:

  1. Extending the Thread Class- Make a class that extends Thread and overrides its run method.
  2. Implement the Runnable Interface - Implement the Runnable interface and pass the instance to a Thread object.

Example of Multithreading in Java:

class MyThread extends Thread {
    private String threadName;

    MyThread(String name) {
        threadName = name;
    }

    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.println(threadName + " is running: iteration " + i);
            try {
                Thread.sleep(500); // Sleep for 500 milliseconds
            } catch (InterruptedException e) {
                System.out.println(e);
            }
        }
        System.out.println(threadName + " has finished running.");
    }

    public static void main(String[] args) {
        MyThread t1 = new MyThread("Thread 1");
        MyThread t2 = new MyThread("Thread 2");

        t1.start(); // Start Thread 1
        t2.start(); // Start Thread 2
    }
}

When the 'run' method of each thread is running at the same time, many threads execute at once.

Output

Thread 1 is running: iteration 1
Thread 2 is running: iteration 1
Thread 1 is running: iteration 2
Thread 2 is running: iteration 2
Thread 1 is running: iteration 3
Thread 2 is running: iteration 3
Thread 1 has finished running.
Thread 2 has finished running.

Multiprocessing vs. Multithreading in Java

FeatureMultiprocessingMultithreading
DefinitionInvolves multiple processes running on different processors or cores.Involves multiple threads running within a single process.
Memory SpaceEach process has its own memory space.Threads share the same memory space and resources.
IsolationHigh isolation between tasks; processes do not share memory.Lower isolation; threads share memory, making communication easier.
SuitabilitySuitable for applications requiring high isolation between tasks.Suitable for applications needing concurrent tasks within the same application.
PerformanceCan leverage multiple processors or cores effectively.Can leverage multi-core processors but within a single process.

Advantages of Multithreading in Java

  • Resource Sharing-Threads share the same memory and resources, making it efficient.
  • Responsiveness-Multithreading can make applications more responsive by performing background operations.
  • Scalability- Utilizing multiple threads can improve the performance of applications on multi-core processors.
  • Simplified Modeling-Suitable for applications that require multiple concurrent activities.

Drawbacks of Multithreading in Java

  • When writing multi-thread programs, we always strive hard to avoid complexities liable to give rise to pitfalls such as deadlocks or even race conditions. 
  • Debugging multithreaded applications is more challenging as compared to the single-threaded ones.
  • Context switching between threads can introduce overhead and affect performance.
Conclusion
This article elaborates on what multithreading in Java is, how it differs from multiprocessing, and explains its pros and cons. To discover more regarding some other concepts in Java Programming, kindly go ahead and sign up for our Java Full Stack Course.

FAQs

Multithreading is a process where many threads can be executed within a single program at once. This helps in resource sharing and increases performance.

Multithreading is of two types that are:
  1. User-Level Threads
  2. Kernel-Level Threads

Multithreading is used in Java so that multiple tasks can be performed together at once and they can efficiently use the CPU resources.

Multithreading is faster as it enables multiple threads to run at once and other tasks can be performed while waiting for I/O operations or other resources.
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this