What Is Multithreading in Java? Thread Lifecycle and Synchronization Explained

Multithreading in Java – Complete Beginner Guide

📘 What is Multithreading?

Multithreading is the process of executing multiple threads simultaneously within a single program.
Each thread represents an independent path of execution.
👉 Multithreading improves performance, responsiveness, and resource utilization.

📌 Real-Life Examples of Multithreading

🎮 Games: One thread handles graphics, another handles user input

🎬 Animations: One thread renders frames, another plays sound

🌐 Web Browsers: One thread loads a page while another scrolls
🏦 Banking App: One thread checks balance while another processes payment

📘 What is a Thread?

  • A Thread is the smallest unit of execution in a Java program.
  • Java supports multithreading using the Thread class and Runnable interface
  • Both are present in the java.lang package

📘 Thread and Runnable Relationship

  • Runnable is an interface
  • It contains only one abstract method: run()
  • Thread class implements Runnable
  • Thread class provides an empty implementation of run()
👉 To create a thread, the programmer must override the run() method

📘 Important Thread Methods

Method.                                 Description
start().                           Starts thread execution
run().                              Contains thread logic
sleep(ms).                     Pauses thread temporarily
currentThread().           Returns current thread
setName().                       Assigns thread name
getName().                      Returns thread name
stop().                       Terminates thread (Deprecated)
⚠️ Note: stop() is deprecated and should not be used in real applications.

📘 start() vs run()

  • start() → Creates a new thread and calls run() internally
  • run() → Executes like a normal method (no new thread)
✔ Always use start() to begin thread execution

📘 Example: Simple Thread Using Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Test {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();
    }
}

📘 Creating Threads in Java
✅ Method 1: By Extending Thread Class

Class becomes a thread type
Object contains all Thread methods

class A extends Thread {
    public void run() {
        System.out.println("Thread A running");
    }
}

✅ Method 2: By Implementing Runnable Interface (Recommended)

  • Better design (supports multiple inheritance)
  • Runnable object must be passed to Thread constructor

class B implements Runnable {
    public void run() {
        System.out.println("Thread B running");
    }
}

Thread t = new Thread(new B());
t.start();

📘 Thread Life Cycle

A thread goes through four main states:

1️⃣ New (Born) State

  • Thread object is created
  • Not yet started

2️⃣ Runnable State

  • start() is called
  • Thread is ready to execute

3️⃣ Blocked / Waiting State

  • Thread is temporarily inactive
  • Caused by sleep(), wait(), or I/O operations

4️⃣ Dead (Terminated) State

  • run() method completes
  • Thread execution ends

📘 Thread Sleep Method

  • sleep() is a static method
  • Makes a thread inactive for a specified time
  • Throws InterruptedException

Thread.sleep(1000); // 1 second

📘 Thread Synchronization
🔒 What is Synchronization?

When multiple threads access a shared resource, it may cause:
  • Data inconsistency
  • Data corruption
👉 Synchronization ensures only one thread accesses a resource at a time

📘 Real-Life Example of Synchronization
🏧 ATM Machine

  • Only one person can withdraw money at a time
  • Prevents incorrect balance updates

📘 Synchronized Method Example

class Account {
    synchronized void withdraw(int amount) {
        System.out.println("Withdrawal in progress");
    }
}

📘 How JVM Handles Synchronization

  • JVM allows only one thread into synchronized method
  • Other threads are placed in thread queue
  • JVM locks the resource using wait()
  • After execution, JVM calls notify() / notifyAll()
  • Next thread from queue is allowed to execute

📘 Important Notes (Exam Focus)

  • Synchronization is applied using synchronized keyword
  • Only instance methods can be synchronized on object level
  • Over-synchronization reduces performance
  • Runnable approach is preferred in real projects

📘 Advantages of Multithreading

✔ Faster execution
✔ Better CPU utilization
✔ Responsive applications
✔ Efficient resource sharing

Comments

Popular posts from this blog

History of Java Programming Language | Features, Origin & Uses

Inheritance in Java: Types, Examples, and Explanation

Java Programming Features Every Beginner Should Know