What is Multithreading in Java

In this tutorial, we will learn what is multithreading in Java and how to implement multithreading using Java program. By Preeti Jain Last updated : January 26, 2024

Java Multithreading

Executing multiple tasks simultaneously is called multithreading.

Each tasks are separate independent part of the same program is called 'Thread'.

It works on program level.

Objective

Main objective of multithreading is to improve performance of the system by reducing response time (i.e. we have 10 employees working on a large project and sudden 20 more employees joined our team to complete the same project so response time will be reduced).

Application

The main important application areas of multithreading are video games, multimedia graphics, animation, etc.

Implementation of Multithreading

Java provides inbuilt support for multithreading by introducing rich API (application programming interface) are Thread, Runable, ThreadGroup, ThreadLocal etc.

Being a developer we have to know how to use API and we are not responsible to define that API (API contains classes, interface, methods etc.)

With the help of multithreading it is very easy to write programs and we can use readymade methods for quick support.

Example

Java program to implement multithreading

// Thread 1 
class Thread1 extends Thread {
  public void run() {
    System.out.println("Thread 1");
  }
}

// Thread 2
class Thread2 extends Thread {
  public void run() {
    System.out.println("Thread 2");
  }
}

// Thread 3
class Thread3 extends Thread {
  public void run() {
    System.out.println("Thread 3");
  }
}

// Main Thread Class
public class Main {
  public static void main(String[] args) {
    Thread1 t1 = new Thread1();
    t1.start();
    
    Thread2 t2 = new Thread2();
    t2.start();
    
    Thread3 t3 = new Thread3();
    t3.start();
  }
}

The output of the above example is:

Thread 1
Thread 2
Thread 3

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.