For Enquiry: 93450 45466

Threads and Multi threading In Java



In this blog, we will dive deeper into understanding the Threads in Java, with these steps…

What are threads in Java?
Thread Life cycle of Java
States Of A Thread
New state
Runnable state
Blocked or Suspended state
Waiting state
Terminated state
Main Thread of Java
Creating a Thread in Java
Create thread using the Thread class
Create thread using the Runnable interface
Multi Threading in Java
Thread Pool in Java

Let us now  dive deep in to each of these topics one by one starting with..

What are Threads in Java?

When you are using your mobile, you might be watching a video or checking messages until the song downloads, or in a common sense you would be using multiple applications at the same time. This is known as multithreading, where each of the applications is running under a thread.

In java, a thread is a lightweight process or smallest independent unit of program which is created and controlled by the java.lang.Thread class.

If you understand well what is a thread in java, let’s move on to our next topic, Java Thread Life Cycle.

Java Thread Life Cycle

Whenever we create a thread, it will have a lifecycle which means it can lie only in one of the shown states at any point of time.Those states are 

New
Runnable
Blocked/Waiting
Terminated 

States Of A Thread

New State

A new thread begins in this state and remains here until the program starts, therefore it is also known as a born thread.

Runnable state

Once a new thread starts, the tread comes under a runnable state where the program is ready to be run or is already running

Waiting State

In the waiting state, a thread is either temporarily inactive or has been blocked and the thread cannot move forward until it is again moved to the runnable state.For instance , when the program is waiting for an input or output to complete, it is under waiting thread.Moreover when a thread is in a blocked or waiting state, there might be any other thread running as scheduled by the thread scheduler.

The threads in waiting or blocked state do not consume any CPU cycle.

Terminated State

A thread enters a terminated state, when the running thread has completed its tasks, or if there is any unusual event like exceptions, segment fault or errors.

These were the states of a java thread, let us now move on to understanding the Main Thread Of Java.

Main Thread Of Java

By default we have a main thread in the java applications which is represented by the main method.The code in main method is executed by the main method in a sequence.So the main thread is created automatically when you run the program, and responsible for performing shut down operations as well.All the other child threads are dependent on the main thread.

Assigning all the tasks to the main method or main thread can make our program slow because of a long running process and can even show the “The program is not responding, do you want to wait or kill the program” dialog box.

This was about the main thread of Java.So let us understand how to create a separate thread in java using the Thread class and the Runnable Interface.

Creating A Thread In Java

Java has a built in support for creating threads, unlike many other programming languages.

A thread in java can be created in two ways:

Using the Thread class
Using the Runnable Interface

Check out this Complete Java Training Online by FITA. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real time applications using Servlets, Hibernate Framework, and Spring with Aspect Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, to make you an industry required certified java developer.

Let us now understand how to create a thread using each of these methods with example programs in java.

Creating threads with Thread class

For Creating threads with Thread class we will just need to extend a custom class with the Thread {class present in java.lang.Thread} using the extend keyword.
The run() method of the Thread class needs to be overridden and provide the instructions to be run by this thread.
Create an object for your class
Invoke the start() method of the Thread class to run or call the custom run() method.
Here is an example of creating a thread in java by extending the Thread class to our custom class

import java.io.*;

 

public class Images extends Thread {

 public void run() {

   System.out.println("The Images app is running");

 }

 

 public static void main(String[] args) {

   Images trd1 = new Images();

   trd1.start();

 }

}

Output for the above program


The Images app is running

Hope you understood creating a single with the Thread class, and now let us see how to create a thread with a runnable interface.

Runnable Interface in Java

In most of the cases your class will be already inheriting any other class , and at the same time to implement the Thread class on it, you cannot inherit the Thread class on the super class, since multiple inheritance is not supported by java,so instead we can use the runnable interface to implement threading.

So creating thread using runnable interface requires the following steps

Create a custom class and implement a runnable interface on it using the implements keyword.
Override the run() method, by providing the code to be executed at that time.
Create an object for the thread class.
Invoke the start() method of the Thread class to run or call the custom run() method.

Here is an example of creating a thread in java by extending the Thread class to our custom class


import java.io.*;

 

public class Videos implements Runnable {

 public void run() {

   System.out.println("The Videos app is running");

 }

 

 public static void main(String[] args) {

   Videos trd2 = new Videos();

   trd2.start();

 }

}

Output for the above program


The videos app is running

Let us understand what is multi threading in Java and how to implement it.

Multi threading in java

So far we have been creating a single thread, and using the 2 threads in a program (main and custom thread). However a program can have more than 2 or multiple threads running each after the other or with a wait in between multiple threads.

There are many methods which helps managing the threads, few of them are:

getName: returns the name of the thread

SYNTAX for getName


public String getName():

getPriority(): returns the priority of the thread

SYNTAX for the getPriority method


public final int getPriority()  

isAlive: returns true or false based on the result of the thread is running or alive

SYNTAX for the isAlive method


public final boolean isAlive()

join: it terminates the currently running thread until the thread it joins with completes all of its tasks and will throw an InterruptedException if the thread it joins has been interrupted

SYNTAX for the join method


public final void join()

run: it executes the main code defined under the run method of the thread.We usually call the run method using the start() method.

SYNTAX for calling the run method


object.start()

sleep: it gives a wait or a pause to the execution of the code for the specified amount of time.

SYNTAX for the sleep method


public static void sleep(long m, int n)

start: It starts the execution of the thread, and calls the run method

SYNTAX for start


public void start() 

Let me show you an example for creating and running multiple threads in an application.


import java.io.*;

 

// Java code for running multiple threads in an application

class Multithreads implements Runnable

{

  public void run()

  {

    try

    {

    

      // Printing the thread which is running

      System.out.println ("Running Thread #" +

                Thread.currentThread().getId());

     for (int j=0; j<5;j++){

       System.out.println ("Do this under Thread " +

                Thread.currentThread().getName());

     }     

      Thread.sleep(1000);

    }

    catch (Exception e)

    {

      // Throwing an exception

      System.out.println ("An Exception is caught while running multiple threads");

    }

  }

}

 

// Main Class

class Mainthread

{

  public static void main(String[] args)

  {

    int n = 10; // Number of threads

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

    {

      Thread trdObj = new Thread(new Multithreads());

      trdObj.start();

    }

  }

}

Output for the above program


Running Thread #13

Running Thread #18

Running Thread #19

Running Thread #16

Running Thread #20

Running Thread #14

Running Thread #15

Running Thread #11

Do this under ThreadThread-7

Do this under ThreadThread-7

Do this under ThreadThread-7

Do this under ThreadThread-7

Do this under ThreadThread-7

Do this under ThreadThread-5

Do this under ThreadThread-5

Do this under ThreadThread-5

Do this under ThreadThread-5

Do this under ThreadThread-5

Do this under ThreadThread-9

Running Thread #17

Running Thread #12

Do this under ThreadThread-1

Do this under ThreadThread-1

Do this under ThreadThread-1

Do this under ThreadThread-1

Do this under ThreadThread-1

Do this under ThreadThread-4

Do this under ThreadThread-4

Do this under ThreadThread-4

Do this under ThreadThread-4

Do this under ThreadThread-4

Do this under ThreadThread-6

Do this under ThreadThread-6

Do this under ThreadThread-6

Do this under ThreadThread-6

Do this under ThreadThread-6

Do this under ThreadThread-8

Do this under ThreadThread-2

Do this under ThreadThread-3

Do this under ThreadThread-9

Do this under ThreadThread-0

Do this under ThreadThread-9

Do this under ThreadThread-3

Do this under ThreadThread-8

Do this under ThreadThread-2

Do this under ThreadThread-3

Do this under ThreadThread-9

Do this under ThreadThread-0

Do this under ThreadThread-9

Do this under ThreadThread-3

Do this under ThreadThread-8

Do this under ThreadThread-2

Do this under ThreadThread-3

Do this under ThreadThread-0

Do this under ThreadThread-0

Do this under ThreadThread-0

Do this under ThreadThread-8

Do this under ThreadThread-2

Do this under ThreadThread-2

Do this under ThreadThread-8

This was all about threads, creating a thread with Runnable Interface and Thread class and multithreading in java along with example programs for implementation.

To get in depth knowledge of core Java and advanced java, J2EE along with its various applications and real-time projects using Servlets, Spring with Aspect Oriented Programming (AOP) architecture, Hibernate Framework,and Struts through JDBC you can enroll in Java Training in Chennai or Java Training in Bangalore by FITA or a virtual class for these courses at an affordable price, bundled with real time projects, certification, support, and career guidance assistance with an active placement cell, to make you an industry required certified java developer.

FITA’s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.





  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai

  • Read More Read less
  • Are You Located in Any of these Areas

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!