Multithreading is a process to execute multiple threads simultaneously. Multiprocessing and multithreading both are used to perform multitasking, Where multitasking is a process to execute the multiple tasks concurrently.
Threads are the lightweight sub process. One process can have multiple threads. They don’t allocate separate memory area so it saves memory and context-switching between the threads takes less time than process. So multithreading is mostly used rather than multiprocessing.
Advantage of Java Multithreading
There are many advantages of multithreading which are as follows:

  1. Threads are independent so it does not affect other thread.
  2. Multiple operations are performed at a time.
  3. Threads share the common memory area so it saves memory.

Life cycle of a Thread
A thread has five stages:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated

life cycle of thread
New:  A new thread starts its life cycle in the new state. It stays in this state until the program invokes the start () method. It is also known as born thread.
Runnable: The new thread goes in this state after invoking start () method but thread scheduler does not select it for running it.
Running: If the thread scheduler has selected the thread then thread goes is in running state.
Blocked: It is also known as Non Runnable state. In this state the thread is still active but is presently not suitable to run.
Terminated: It is also known as dead state. A thread enters in this when it completes its task.
Create Thread
There are two ways to create a thread:

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

1. By extending Thread class
Another way to create a thread is to create a new class that extends Thread class. It gives more flexibility in handling multiple threads created using available methods in Thread class.

class Intellipaat extends Thread{
public void run(){   // Perform action for a thread
System.out.println("Thread is created by extending Thread class");
Thread.sleep(50);}   // Sleep a thread for the specified amount of time.
catch(InterruptedException e){System.out.println(e);}
public static void main(String args[]){
Intellipaat i=new Intellipaat();
i.start();  // Start a newly created thread

Thread is created by extending Thread class
2. By implementing Runnable interface
If class is executed as a thread then you can accomplishthis task by implementing Runnable interface.

class Intellipaat implements Runnable{
public void run(){
System.out.println("Thread is created by implementing runnable interface");
public static void main(String args[]){
Intellipaat i=new Intellipaat();
Thread t =new Thread(i);

Thread is created by implementing runnable interface
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Leave a Reply

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

Solve : *
5 + 18 =