Understanding Multithreading in Java with Examples

Understanding Multithreading in Java with Examples

10 Jun 2024
Intermediate
134 Views
9 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

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 Certification Training 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 Certification Course!

FAQs

Q1. What is multithreading and its benefits?

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

Q2. What is multithreading types?

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

Q3. Why is multithreading used in Java?

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

Q4. Why is multithreading faster?

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

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Project Jul 16 TUE, THU
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Azure Master Class Jul 20 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this