---Advertisement---

Multithreading in Java: A Complete Guide

By Shiva

Published On:

---Advertisement---

Multithreading in Java:

Multithreading in Java is a programming technique that allows concurrent execution of two or more threads. It helps in maximizing CPU utilization and improving application performance. By running multiple threads simultaneously, Java applications can perform multiple operations without blocking execution.

  • Efficient CPU Utilization – Enables multiple tasks to execute in parallel.
  • Faster Execution – Reduces execution time for CPU-intensive applications.
  • Independent Processes – If one thread fails, others continue execution.
  • Better Responsiveness – Useful for applications like games, GUI-based programs, and real-time systems.

A single-threaded application executes one task at a time. Java uses the Thread class to create and manage threads. The main method runs as a single thread by default.

Example of a Single Thread:

public class SingleThreadExample {
    public static void main(String[] args) {
        System.out.println("Executing a Single Thread");
    }
}

Multithreading allows execution of multiple threads concurrently, improving application efficiency.

Example of Multi-threading:

class MultiThreadExample implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running");
    }
    
    public static void main(String[] args) {
        Thread thread1 = new Thread(new MultiThreadExample(), "Thread 1");
        Thread thread2 = new Thread(new MultiThreadExample(), "Thread 2");
        
        thread1.start();
        thread2.start();
    }
}
FeatureSingle ThreadMultithreading
ExecutionOne task at a timeMultiple tasks concurrently
CPU UsageNot fully utilizedFully utilized
SpeedSlower executionFaster execution
ResponsivenessBlocks applicationKeeps app responsive

A Java thread undergoes multiple stages during its execution:

  1. New – The thread is created but not yet started.
  2. Runnable – The thread is ready to run but waits for CPU allocation.
  3. Running – The thread is executing its assigned task.
  4. Waiting – The thread is waiting for another thread to complete.
  5. Terminated (Dead) – The thread execution is complete.
 New β†’ Runnable β†’ Running β†’ Waiting β†’ Terminated

Java provides several built-in methods to manage threads efficiently.

MethodDescription
start()Begins thread execution.
sleep(milliseconds)Pauses the thread for a specified duration.
getName()Returns the name of the thread.
setPriority(int level)Sets thread priority.
yield()Allows other threads to execute first.

Example of Thread Methods:

class ThreadMethodsExample extends Thread {
    public void run() {
        System.out.println("Thread " + getName() + " is running");
    }
    
    public static void main(String[] args) {
        ThreadMethodsExample t1 = new ThreadMethodsExample();
        t1.setName("MyThread");
        t1.start();
    }
}

In a multithreaded environment, multiple threads may access shared resources, leading to data inconsistency. Java provides synchronization to ensure only one thread accesses critical code at a time.

Example of Synchronization:

class SyncExample {
    synchronized void printNumbers(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

class Thread1 extends Thread {
    SyncExample obj;
    Thread1(SyncExample obj) {
        this.obj = obj;
    }
    public void run() {
        obj.printNumbers(5);
    }
}

class Thread2 extends Thread {
    SyncExample obj;
    Thread2(SyncExample obj) {
        this.obj = obj;
    }
    public void run() {
        obj.printNumbers(10);
    }
}

public class SynchronizationDemo {
    public static void main(String[] args) {
        SyncExample obj = new SyncExample();
        Thread1 t1 = new Thread1(obj);
        Thread2 t2 = new Thread2(obj);
        
        t1.start();
        t2.start();
    }
}
  • Prevents data inconsistency
  • Ensures data integrity
  • Controls thread interference

  • Multithreading in Java improves performance by running multiple tasks in parallel.
  • The Thread lifecycle includes states: New, Runnable, Running, Waiting, and Terminated.
  • Java provides built-in thread methods such as start(), sleep(), and yield().
  • Synchronization helps prevent data inconsistency by controlling thread execution.

By using multithreading effectively, Java developers can build highly responsive and efficient applications. πŸš€

---Advertisement---

Leave a Comment