Java Multithreading

Multithreading in Java is a technique that allows multiple threads (smaller units of a process) to run concurrently within a program, thereby making better use of the CPU and improving the overall performance of an application. It allows multiple tasks to be executed at the same time in a single program, making it suitable for performing complex or resource-heavy tasks concurrently.

In Java, threads are lightweight processes, and each thread has its own execution path. Java provides built-in support for multithreading through the Thread class and the Runnable interface.

Example: Using the Thread class


//Main.java file
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Create two threads
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        
        // Start both threads
        t1.start();
        t2.start();
    }
}

Output:

15 Value 0
15 Value 1
14 Value 0
14 Value 1

Example: Using the Runnable interface


//Main.java file
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getId() + " Value " + i);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Runnable object
        MyRunnable myRunnable = new MyRunnable();
        
        // Create two threads using the Runnable object
        Thread t1 = new Thread(myRunnable);
        Thread t2 = new Thread(myRunnable);
        
        // Start both threads
        t1.start();
        t2.start();
    }
}

Output:

15 Value 0
15 Value 1
14 Value 0
14 Value 1