INSTACK 360

Java Multithreading & Concurrency

Learn how to execute multiple threads simultaneously to maximize CPU utilization in Java.

Advanced 5 min read

What is Multithreading?

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Creating a Thread

Threads can be created by using two mechanisms:

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

Example: Extending Thread Class

class MultithreadingDemo extends Thread {
    public void run() {
        try {
            System.out.println("Thread " + Thread.currentThread().getId() + " is running");
        } catch (Exception e) {
            System.out.println("Exception is caught");
        }
    }
}

public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            MultithreadingDemo object = new MultithreadingDemo();
            object.start(); // Triggers the run() method
        }
    }
}

Thread Synchronization

When multiple threads try to access the same resources, they may produce erroneous results. Java provides synchronization to ensure that only one thread can access a resource at a given point in time using the synchronized keyword.