Multithreading in Java

Site Admin · 11 Sep 2026 · 11 views

Doing Many Things at Once

A thread is an independent path of execution inside a program. By splitting work across threads, a program can use more of the CPU and keep the user interface responsive while heavy jobs run in the background.

Creating Threads - Option 1: Extending Thread

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Running in: " + getName());
    }
}

MyThread t = new MyThread();
t.start(); // the JVM schedules run() separately

Creating Threads - Option 2: Runnable Interface

Preferred because the class can still extend another class.

class PrintJob implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
}

Thread t = new Thread(new PrintJob(), "Worker-1");
t.start();

Thread Lifecycle

NEW (created) -> RUNNABLE (started, waiting for CPU) -> RUNNING -> BLOCKED/WAITING -> TERMINATED (finished).

sleep and join

Thread.sleep(1000);      // pause this thread for 1 second
Thread worker = new Thread(new PrintJob());
worker.start();
worker.join();           // wait here until worker finishes
System.out.println("Worker completed");

Lambda Alternative (Java 8+)

Thread t = new Thread(() -> System.out.println("From a lambda"));
t.start();

Thread life cycle

Key Points

  • Implement Runnable or extend Thread; override run().
  • Call start(), never run() directly, to get a real thread.
  • sleep pauses; join waits for another thread.
Share this post:

Comments (0)

Please login or register to comment.