Skip to main content

Command Palette

Search for a command to run...

Java Series #6: Multitasking, Multithreading & Thread Creation Explained

Understanding Concurrency and Threading in Modern Java

Published
3 min read
Java Series #6: Multitasking, Multithreading & Thread Creation Explained
A

I am a Full-stack dev turning ideas into sleek, functional experiences 🚀. I am passionate about AI, intuitive UI/UX, and crafting user-friendly platforms . I am always curious – from building websites to diving into machine learning and under the hood workings ✨. Next.js, Node.js, MongoDB, and Tailwind are my daily tools. I am here to share dev experiments, lessons learned, and the occasional late-night code breakthroughs. Always evolving, always building.

This article breaks down multitasking, multithreading, thread creation, and thread control with clear explanations and examples.

Multitasking vs Multithreading

What is Multitasking?

Multitasking means running multiple processes simultaneously on a single CPU. The operating system rapidly switches between processes to give an illusion of parallel execution.

Example:
Running Chrome, PowerPoint, VS Code, and Spotify at the same time.
Each one is a separate process with its own memory space.

What is Multithreading?

Multithreading refers to running multiple threads within a single process. Threads share memory and resources, which makes communication easier and execution faster.

Example in a Web Browser:

  • One thread loads the webpage

  • One thread downloads a file

  • One thread plays a video

  • One thread handles user input

All of these threads belong to the same browser application.

Advantages of Multithreading in Java

  1. Parallel execution of tasks

  2. High responsiveness in applications

  3. Better CPU utilization

  4. Efficient use of system resources

Disadvantages of Multithreading

  1. Deadlocks due to incorrect resource locking

  2. Race conditions when threads access shared data without synchronization

  3. More complex debugging and testing

  4. Overhead due to thread scheduling


Creating Threads in Java

Java provides two primary ways to create threads:

1. Extending the Thread Class

This approach is useful when your class does not already extend another class.

Steps

  1. Create a class that extends Thread

  2. Override the run() method

  3. Create an instance of the class

  4. Call start() to begin execution

Example

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

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

2. Implementing the Runnable Interface

This is the preferred approach, especially when your class already extends another class. Java avoids multiple inheritance to prevent the diamond problem, so implements Runnable becomes more flexible.

Steps

  1. Implement the Runnable interface

  2. Provide an implementation for run()

  3. Wrap your runnable object inside a Thread object

  4. Call start() on the Thread instance

Example

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Runnable thread is running...");
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
    }
}

When to Use Which?

Use extends Thread when:

  • Your class does not extend any other class.

Use implements Runnable when:

  • Your class already extends a parent class.

  • You want better separation between task logic and thread execution.


Thread.sleep() in Java

The sleep() method is used to pause the currently executing thread for a specified duration. This is useful when implementing delays, animations, timers, or background tasks.

Example

class PrinterThread extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Printing: " + i);
            try {
                Thread.sleep(1000); // pause for 1 second
            } catch (InterruptedException e) {
                System.out.println("Thread interrupted");
            }
        }
    }
}

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

Explanation

  • The loop runs five times.

  • After each print, the thread pauses for one second.

  • InterruptedException must be handled because another thread may interrupt the sleeping thread.

Multithreading is one of Java’s strongest features, enabling developers to build scalable and responsive applications. Understanding the difference between multitasking and multithreading, along with mastering thread creation techniques, forms a strong foundation for mastering concurrency in Java.