What is Thread in java || Multiple threading in Java

As we know, Java is a multi-threaded programming language which means we can develop a multi-threaded program using Java and this multi-threaded program contains two or more parts which can run concurrently that help to handle a different task at the same time making optimal use of the available resources especially when your computer has multiple CPUs.

If we start from the definition, multitasking is when multiple processes share common processing resources such as a CPU.

Multi-threading basically extends the idea of multitasking into the application level where you can subdivide specific operations within a single application into individual threads.

By the way, each of the threads is able to run in parallel and the OS divides easily this processing time not only among different applications but also among each thread within an application.

Multi-threading also enables you to write in a way where multiple activities can proceed concurrently in the same program.

Life Cycle of a Thread

Mainly, the thread goes through various stages in its life cycle. For example, a thread is born and started, runs, and then dies.

Following are the stages of the life cycle of thread −

New  A new thread begins its life cycle or started his journey in the new state. It always remains in this state until the program starts the thread. It is also referred sometimes as a born thread.

Runnable  After a newly born thread is started, it mainly becomes runnable. And this state is considered to be executing its task.

Waiting  Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transition back to the runnable state only when another thread passes the signals the waiting thread to continue executing.

Timed Waiting  This is a runnable thread that can enter the timed in the waiting state for a specified interval of time. In this state thread transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

Terminated (Dead) A runnable thread that enters the terminated state when it completes its task or terminates directly by another thread.

Thread Priorities

As we know every Java thread has a priority that helps the operating system to determine the order in which threads are scheduled or not.

These thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is always given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are most important to a program because it helps to allocated processor time before lower-priority threads. Meanwhile, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.

Thread creation by extending the java.lang.Thread class.

class MultithreadingExample extends Thread

{

    public void run()

    {

        try

        {

            // Displaying the thread that is running

            System.out.println ("Thread " +

                  Thread.currentThread().getId() +

                  " is running");

  

        }

        catch (Exception e)

        {

            // Throwing an exception

            System.out.println ("Exception is caught");

        }

    }

}

  

// Main Class

public class Multithreads

{

    public static void main(String[] args)

    {

        int n = 9; // Number of threads

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

        {

            MultithreadingExample object = new MultithreadingExample();

            object.start();

        }

    }

}



Output:

Thread 21 is running

Thread 23 is running

Thread 22 is running

Thread 24 is running

Thread 25 is running

Thread 26 is running

Thread 27 is running

Thread 28 is running

Thread 29 is running

Thread creation by implementing the Runnable Interface

 

// Java code for thread creation by implementing

// the Runnable Interface

class MultithreadingExample implements Runnable

{

    public void run()

    {

        try

        {

            // Displaying the thread that is running

            System.out.println ("Thread " +

                                Thread.currentThread().getId() +

                                " is running");

  

        }

        catch (Exception e)

        {

            // Throwing an exception

            System.out.println ("Exception is caught");

        }

    }

}

  

// Main Class

public class Multithread

{

    public static void main(String[] args)

    {

        int n = 9; // Number of threads

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

        {

            Thread object = new Thread(new MultithreadingExample());

            object.start();

        }

    }

}

 


Output :

Thread 21 is running

Thread 22 is running

Thread 23 is running

Thread 24 is running

Thread 25 is running

Thread 26 is running

Thread 27 is running

Thread 28 is running

Thread 29 is running

 Thread Class vs Runnable Interface

1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritances. But, if we implement the Runnable interface, our class can still extend other base classes.

2. We can achieve the basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt(), etc. that are not available in the Runnable interface.