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.






Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


Read More Read less

FITA Academy Branches

Chennai

Bangalore

Coimbatore

Other Locations

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

FITA Academy - Tiruppur
61D, Poongodi Towers 2nd floor,
Periyar Colony Bus Stop,
Tirupur - 641 652

    :   9940122502

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

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur 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!