Introduction to Threads in Java

8/16/2025
All Articles

Java threads explained with examples of Thread class, Runnable interface, and thread lifecycle

Introduction to Threads in Java

Introduction to Threads in Java


What are Threads in Java?

A thread in Java is the smallest unit of a process that can execute independently. Threads allow a program to perform multiple tasks simultaneously, making applications more responsive and efficient. The use of multithreading is especially important in modern applications that require concurrency, such as real-time systems, games, or web servers.

Java provides built-in support for threads via the java.lang.Thread class and the Runnable interface.


Why Use Threads in Java?

  • Improves performance through parallel execution.

  • Enhances responsiveness in applications (e.g., GUIs).

  • Utilizes CPU resources more efficiently.

  • Simplifies asynchronous and background tasks.


Creating Threads in Java

There are two common ways to create threads in Java:

1. Extending the Thread Class

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

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

2. Implementing the Runnable Interface

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

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyRunnable());
        t1.start();
    }
}

Thread Lifecycle in Java

A thread in Java goes through the following states:

  1. New → Created but not started.

  2. Runnable → Ready to run.

  3. Running → Actively executing.

  4. Waiting/Timed Waiting → Waiting for another thread or event.

  5. Terminated → Completed execution.


Example of Multiple Threads

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

    public static void main(String[] args) {
        MultiThreadExample t1 = new MultiThreadExample();
        MultiThreadExample t2 = new MultiThreadExample();

        t1.start();
        t2.start();
    }
}

Output:

Thread-0 is running
Thread-1 is running

Advantages of Using Threads

  • ✔ Better resource utilization

  • ✔ Faster execution through parallelism

  • ✔ Simplifies complex asynchronous tasks

Disadvantages

  • Increased complexity in debugging

  • Risk of deadlocks and race conditions

  • Higher memory consumption with too many threads


Final Thoughts

Threads are a core feature of Java’s concurrency model, enabling developers to build responsive and high-performance applications. Understanding thread creation, lifecycle, and best practices is crucial for writing scalable and efficient Java programs.

Article