Multi-threading in Java

Multi-tasking
What is Multi-threading ?
What are threads ?

Java Multithreading

[Note :** There can be multiple processes inside the OS, and one process can have multiple threads.

How to create threads ?

Threads can be created by using two mechanisms :

  1. Extending the Thread class
  2. Implementing the Runnable Interface

1. Extending the Thread Class

// Java code for thread creation by extending the Thread class 
class MultithreadingDemo 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 Multithread { 
    public static void main(String[] args) {
        int n = 8; // Number of threads 
        for (int i=0; i<n; i++) { 
            MultithreadingDemo object = new MultithreadingDemo(); 
            object.start(); 
        } 
    } 
} 

Output:

Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

2. Implementing the Runnable Interface

// Java code for thread creation by implementing the Runnable Interface 
class MultithreadingDemo 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 
class Multithread { 
    public static void main(String[] args) { 
        int n = 8; // Number of threads 
        for (int i=0; i<n; i++) { 
            Thread object = new Thread(new MultithreadingDemo()); 
            object.start(); 
        } 
    } 
} 

Output:

Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 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 inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

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