DEV Community

Mohammed mhanna
Mohammed mhanna

Posted on

⚡ Mastering Multithreading in Java

Ever noticed how your computer does multiple things at once — like downloading files while you type? That’s multithreading in action.

In Java, multithreading lets you run several parts of a program simultaneously, improving performance and responsiveness. Let’s break it down step by step.


🧠 What Is Multithreading?

Multithreading means executing multiple threads at the same time.

🧩 A thread is the smallest unit of a process that can run independently.

Think of it like a kitchen:

👩‍🍳 Each chef = a thread

🍝 The dish = your program

🏠 The kitchen = your CPU

Having multiple chefs (threads) allows faster cooking (execution).


🔍 Why Use Multithreading?

Here’s why Java developers use multithreading every day:

✅ Better performance on multi-core processors
✅ Smoother user experience (no freezing UI)
✅ Efficient CPU utilization
✅ Useful for tasks like file I/O, web requests, or background processing


🧩 How Threads Work in Java

In Java, every program starts with one main thread — the one that runs the main() method.

To add more threads, you have two main options:

💻 1. Extending the Thread Class

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

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // starts a new thread
        System.out.println("Main thread: " + Thread.currentThread().getName());
    }
}
Enter fullscreen mode Exit fullscreen mode

🧠 Key points:

Always call start(), not run().

start() creates a new thread and calls run() internally.


💡 2. Implementing the Runnable Interface

A more flexible approach — especially when your class already extends another one.

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Running thread via Runnable: " + Thread.currentThread().getName());
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}
Enter fullscreen mode Exit fullscreen mode

✅ This approach is preferred in real-world Java projects.


⚙️ 3. Using ExecutorService (Modern Approach)

Java introduced the Executor framework to manage multiple threads efficiently.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 5; i++) {
            int task = i;
            executor.submit(() -> System.out.println("Task " + task + " on " + Thread.currentThread().getName()));
        }

        executor.shutdown();
    }
}
Enter fullscreen mode Exit fullscreen mode

🧰 Why use Executors?

You control the number of threads.

You can reuse them (thread pooling).

It simplifies managing background tasks.

📚 Learn more: Java ExecutorService Documentation


🧮 Thread States in Java

A thread doesn’t just run — it moves through different states:

NEW → RUNNABLE → RUNNING → BLOCKED/WAITING → TERMINATED

Example:
When you call start() → thread becomes RUNNABLE.
When the task finishes → thread becomes TERMINATED.


🚦 Thread Synchronization

When multiple threads access shared data, problems can occur (race conditions).

Example: two threads updating the same variable at once.

To prevent that, use synchronization:

class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode

🔐 The synchronized keyword ensures that only one thread accesses that method at a time.


⚡ Real-World Examples of Multithreading

Downloading multiple files at once

Processing multiple user requests in a web server

Running background tasks in Android apps

Updating live dashboards or games

🧠 Once you understand threads, you’ll start seeing them everywhere in software development.


🧰 Helpful Tools & Libraries

Here are some tools to help you practice and visualize multithreading:

VisualVM
→ Monitor thread activity in real-time

JConsole
→ View running threads

Concurrency Utilities (java.util.concurrent)


🎯 Final Thoughts

Multithreading is where Java gets powerful — but also tricky.

Start small:
✅ Create simple threads
✅ Learn synchronization
✅ Explore ExecutorService

With time, you’ll understand how to write programs that are both fast and safe.


💬 Question for You

Have you tried using threads in your projects yet?
What’s the most challenging part about understanding concurrency for you?

Drop your thoughts below 👇

Top comments (0)