View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Multithreading in Java – Learn with Examples

By Pavan Vadapalli

Updated on Feb 17, 2025 | 6 min read | 5.3k views

Share:

Java is a programming language that supports multithreaded programs. Multithreaded programs accommodate two or more parts (threads) that run simultaneously, handling different tasks, enabling optimal CPU usage. Multi-threading is an extension of multi tasking. Multi tasking can be defined as a feature where multiple processes share a common processing resource like a central processing unit. 

Multithreading branches out the concept of multi-tasking to various applications where defined operations can be broken down into smaller individual threads.

Each of these threads runs simultaneously and independently with different execution paths such that an exception in one thread does not affect the performance of others. 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

What is Multithreading in Java?

Multithreading in Java is where multiple threads are executed simultaneously to maximize the CPU time.

Life Cycle of a Thread

Threads have different stages in their life cycle. They are as follows:

  • New: The thread begins its life cycle as a new thread. It remains in this newborn stage until a program runs the thread. 
  • Runnable: A born thread enters the runnable stage when a program initiates it. The thread starts executing its task in this stage.
  • Waiting: This is a transition stage where a thread waits for another thread to complete its task. A thread in the waiting stage switches to a runnable stage after receiving a signal from other threads.
  • Timed waiting: This is a stage that a runnable thread can enter for a specific time interval. Threads in this stage move back to the runnable stage at the end of the specific time interval. 
  • Dead: This is the final stage in the life cycle of a thread. A thread enters this stage after completing its task. 

Benefits of Multithreading in Java

  • As threads in Java are independent, Java multithreading does not block the users, and they can perform many operations simultaneously. 
  • As multithreading in Java enables multiple operations, it is time-saving and efficient. 
  • The program can run continuously even if a part of it is intercepted.
  • It improves the performance against the conventional parallel programs that use multiple processes.
  • Creation of efficient programs that utilize the CPU time to its fullest.
  • Greatly improves the response time of complex applications. 
  • Requires fewer resources compared to traditional parallel programs.

Order of Thread Priority

The operating system determines the thread’s execution schedule based on the thread’s priority. A thread’s priority is determined based on its constant’s value. 

  • Constant 1 gets minimum priority ( MIN_PRIORITY)
  • Constant 5 gets normal priority ( NORM_PRIORITY)
  • Constant 10 gets the maximum priority (MAX_PRIORITY)

How to create a thread in Java?

Threads can be created in Java in two ways:

  1. Extending thread class
  2. Implementing a runnable interface

Creating a Thread by Extending Thread Class

A few methods of thread class and their functions are given below. 

  • getName() : For obtaining thread’s name
  • getPriority(): To obtain thread’s priority
  • is Alive(): to find if a thread is running 
  • join(): wait for a thread’s termination
  • run() : Point of thread’s entry
  • sleep(): For suspending a thread for a specific time window.
  • start() : To activate a thread through its run() method.

Step 1: Override the run() method given in the thread class. This acts as the entry point for the thread, and the entire program logic should be encased in 4this. 

The syntax of the run() method is as follows:

public void run ( )

Step 2:  Initiate the thread object by start () method whose syntax is a void start ( )

Here are examples of a multithreading program in Java:

Example 1:

class MultithreadingDemo extends Thread{  

  public void run(){  

    System.out.println(“My thread is running.”);  

  }   

  public static void main(String args[]){  

     MultithreadingDemo obj=new MultithreadingDemo();   

     obj.start();  

  }  

}

The output of the above program will be:

My thread is running.

Example 2: 

class Count extends Thread

{

   Count()

   {

     super(“my thread is extending”);

     System.out.println(“my thread is created” + this);

     start();

   }

   public void run()

   {

     try

     {

        for (int i=0 ;i<10;i++)

        {

           System.out.println(“Printing the count ” + i);

           Thread.sleep(1000);

        }

     }

     catch(InterruptedException e)

     {

        System.out.println(“my thread got interrupted”);

     }

     System.out.println(“My thread is over” );

   }

}

class ExtendingExample

{

   public static void main(String args[])

   {

      Count cnt = new Count();

      try

      {

         while(cnt.isAlive())

         {

           System.out.println(“Main thread will be alive till the child thread lives”);

           Thread.sleep(1500);

         }

      }

      catch(InterruptedException e)

      {

        System.out.println(“Main thread got interrupted”);

      }

      System.out.println(“Main thread’s run is terminated” );

   }

}

The output of the above program will be 

my thread is createdThread[my runnable thread,5,main]

Main thread will be alive till the child thread lives

Printing the count 0

Printing the count 1

Main thread will be alive till the child thread lives

Printing the count 2

Main thread will be alive till the child thread lives

Printing the count 3

Printing the count 4

Main thread will be alive till the child thread lives

Printing the count 5

Main thread will be alive till the child thread lives

Printing the count 6

Printing the count 7

Main thread will be alive till the child thread lives

Printing the count 8

Main thread will be alive till the child thread lives

Printing the count 9

my thread run is terminated

Main thread run is terminated

Creating a Thread by Implementing a Runnable Interface

There are three important steps to be followed while using this method. 

Step 1: A run() method should be implemented by a runnable interface. This run() method acts as the entry point for the thread and should contain the entire program logic. 

Syntax for the run() method is 

public void run( )

Step 2:  A thread object should be activated using the constructor given below.

Thread(Runnable threadObj, String threadName);

Here threadObj acts as the class that implements the runnable interface, and thread name is the name given to the new thread.

Step 3: After creating the thread object, it can be initiated by the start() method that executes the run() method. 

The syntax of the start () method is as follows.

void start();

An example of creating a thread by implementing a runnable interface can be found here.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Executive PG Program in Software Development is a 13-month online program designed to help working professionals take a giant leap in their careers through industry-relevant case studies and projects. The program also includes over ten live sessions from the industry experts to help the candidates learn better. 

The program includes industry projects to help the candidates have hands-on experience and adequate industry exposure to make their learning relevant and practical. The completion of the program will reward the candidates with the coveted IIIT B certification and alumni status. 

The program comes with 360-degree placement support from upGrad that has impacted over 40,000 paid learners from all corners of the world to make things even better. upGrad has a learners base from over 85 countries providing a priceless opportunity to have a global peer network for the candidates. 

Frequently Asked Questions (FAQs)

1. What is the difference between multitasking and multithreading in Java?

2. Is multiple inheritance supported by Java?

3. Can multithreading improve the performance of Java?

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad

Microsoft | upGrad KnowledgeHut

Microsoft Azure Data Engineering Certification

Access Digital Learning Library

Certification

45 Hrs Live Expert-Led Training

View Program
upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

View Program