Multithreading in Java

  • By
  • February 4, 2022
  • JAVA

Multithreading  in Java –

Before going to start with Multithreading in java, let’s try to understand what is meant by thread which is nicely described by trainers of Java Training In Pune?

What is Thread in java?

A thread is a lightweight sub process that runs in the background of the main process. Threads are executed separately in the memory . Threads are independent. If exception is occurred in one thread then because of that thread other threads won’t be affect. Thread uses a shared memory area.  

Why do we use threads in programming?

Because, Threads allows a program to work more efficiently by doing multiple things simultaneously. Threads can perform tedious tasks in the background without disrupting the main program.

Example,

When we work with any word document, there is one spell checker thread which checks for the grammatical and spelling mistake error at a time of typing that document by the user. It warns the user every time if he made any spelling or grammatical mistake by generating a red or green line below the incorrect word and because of this the user is able to repair his mistake. There is also a font checker, font size checker and color checker thread is there to set the color and font of the previous letter to the next letter of the document which is being typed by the user. In short, threads help the user to perform his task accurately, efficiently and speedily. Almost every application/process contains thread. 

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

 

What is Multithreading in Java?

Multithreading is one of the features of java that allows concurrent execution of two or more parts of a program for maximum utilization of CPU and that each part is  called a thread. Multithreading is also called Concurrency in Java because one or more threads executes parallel in the system. 

We have multiple  processes inside the OS, and one process could have multiple threads. We can achieve multitasking with the help of Multiprocessing and multithreading.

  1. To execute multiple threads simultaneously is called multithreading. For example, spell checker, font checker.
  2. To execute multiple processes simultaneously is called as multiprocessing For example, save, and open.
  3. To perform multiple tasks simultaneously is called multitasking. For example, typing in word documents, browsing on the internet, and typing programs in eclipse.

Advantages of Java Multithreading –

  1. In multithreading, since multiple threads execute at the same time, you can perform many operations together, so it saves time.
  1. Thread shares the common memory area; no extra memory will be required for running the thread. Hence, it saves the memory space.
  1. One thread is not dependent upon another thread, so it doesn’t affect another thread if an exception occurs in a single thread.

LIFE CYCLE/states/ phases  of a Thread –

According to the sun micro system, there are only 4 states in thread life cycle in java: new, runnable, non-runnable and terminated. There is no running state. But to better understand the threads, Java Classes In Pune are explaining it in the 5 states.

The life cycle of the thread in java is managed  by JVM. 

1. New

2.Runnable

3.Running

4.Non-Runnable (Blocked)

5.Terminated

 

  1. New –

The thread is in a new state when the object of thread class is created, but before execution of start method calling.

  1. Runnable –

The thread is in a runnable state after calling the start() method, but it is not selected by  the thread scheduler as a running thread.

  1. Running –

The thread is in running state when thread scheduler has selected it for the execution 

  1. Non-Runnable (Blocked) –

This is the state when the thread is not dead,, but is currently not eligible to run.

  1. Terminated –

A thread is in dead state when the execution of run method gets finished.

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

 

Ways to create a thread in the programming –

There are two ways by which we can create thread in java

  1. By extending Thread class
  2. By implementing Runnable interface

 

1.By extending Thread class –

Java provides Thread class to achieve thread programming. In this way thread can be created by extending the Thread class and overriding its run method. Here, thread can be run by creating an object of thread class and call its run() method.

Thread class having some  constructors and methods to create and perform operations on threads in java. 

Thread class extends Object class and implements Runnable interface.

Every program by default has one thread called as main thread. because all the execution of program done by the main thread 

Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

 

1.Thread()

2.Thread(String name)

3.Thread(Runnable r)

4.Thread(Runnable r,String name)

 

Program that creates a thread by  extending Thread class –

package multithreadingPrograms;

 

class A11 extends Thread

{

         //it is mandatory to define run() in every class in which you want to create a thread. this //method perform task or begin action that you want to execute

 

public void run()     

{

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

{

System.out.println(“Thread A : “+i);          //0,1

    try 

                           {  

sleep(500);

                            } 

                          catch(Exception e) 

 {

 }        //1000 ms = 1 second              

}

System.out.println();

}

}

 

class B11 extends Thread

{

public void run()

{

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

{

System.out.println(“Thread B : “+i);//0,1                  

          Try

 { 

     sleep(500);

  } 

catch(Exception e)

  {

  }

}

}

}

 

public class CreateThread2 {

 

public static void main(String[] args) {

 

           A11 a=new A11();

            a.start();

 //calling start()  method.  When we call start() method, the start() itself calls run() method of Thread class automatically. If we are not called start() then thread execution cannot start.

   //it is mandatory to call start()     

if you want to execute thread

            

                 B11 b=new B11();

          b.start();

        

}

 

}

/*

 output

 

Thread A : 0

Thread B : 0

Thread A : 1

Thread B : 1

Thread A : 2

Thread B : 2

Thread A : 3

Thread B : 3

Thread A : 4

Thread B : 4    */

 

  1. By implementing Runnable interface

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. 

 

Runnable interface have only one method named  run().

 

public void run(): is used to perform action for a thread.

 

If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object’s constructor and then calling the thread’s start() method.

 

//program to create Thread by implementing Runnable interface

 

package multithreadingPrograms;

 

class Aa implements Runnable

{

  public void run()    //it is mandatory to define run() in every class in which you want   

             //to create a thread. this method perform task or begin action   

 

                        //that you want to execute

  {

  

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

  {

System.out.println(“Thread A : “+i);

Try

 { 

     sleep(500);

  } 

catch(Exception e)

  {

  }

 

 

      }

 

  }

}

 

class Bb implements Runnable

{

  public void run()

  {

  

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

  {

System.out.println(“Thread B : “+i);

Try

 { 

     sleep(500);

  } 

catch(Exception e)

  {

  }

 

      }

 

  }

}

public class RunnableDemo {

 

public static void main(String[] args) {

// TODO Auto-generated method stub

   

Aa o1= new Aa();

        Thread t1=new Thread(o1);     //If the class implements the Runnable interface, the    

 

//thread can be run by passing an instance of the class //to a Thread object’s constructor and then calling the thread’s //start() method.

        

        t1.start();         

                       

        Bb o2= new Bb();

        Thread t2 = new Thread(o2);

        

        t2.start();

        

     }

 

}

 

/*

 * output:

 

 

Thread A : 0

Thread B : 0

Thread A : 1

Thread B : 1

Thread A : 2

Thread B : 2

Thread A : 3

Thread B : 3

Thread A : 4

Thread B : 4   */

For Free, Demo classes Call: 8237077325
Registration Link: Click Here!

 

Java Course In Pune can’t predict output of the program of thread class, because which thread will get execute first that we don’t know.

 

Author:-

Pooja Nandode-Bhavsar

Call the Trainer and Book your free demo class for now!!!

© Copyright 2020 | Sevenmentor Pvt Ltd.

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*