Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconMultithreading in Java – Learn with Examples

Multithreading in Java – Learn with Examples

Last updated:
22nd Jun, 2022
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Multithreading in Java – Learn with Examples

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.

Ads of upGrad blog

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)

Popular Courses & Articles on Software Engineering

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.

To learn more about Java multithreading and software development, we recommend enrolling in the Executive Post Graduate Program in Software Development offered by IIIT Bangalore in association with upGrad.

Ads of upGrad blog

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. 

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

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

Multitasking is the process by which many tasks can be performed simultaneously, and multithreading is the process of executing multiple threads at the same time, with each thread performing a different task.

2Is multiple inheritance supported by Java?

The programming language Java supports multiple inheritance, a process in which a class implements more than one interface. A class can have different implementations of a method (default or static) in the interfaces. Multiple inheritance in Java can be implemented only with interfaces and not classes, unlike the C++ language.

3Can multithreading improve the performance of Java?

Multithreading improves the performance of Java by enabling multiple CPUs to attend to the same issue. This not only speeds up the process but also helps in efficient problem-solving.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6085
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas &#038; Topics
12775
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions &#038; Answers [For Freshers &#038; Experienced]
5676
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions &#038; Answers in US [2024]
5396
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas &#038; Topics For Beginners [US 2023]
11003
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5460
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5560
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5042
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5534
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon