Thread Class in Java
The Thread class in java.lang is one of the two primary ways to create a thread in Java. When you extend Thread, you override its run() method to define th...
Extending the Thread Class
The Thread class in java.lang is one of the two primary ways to create a thread in Java. When you extend Thread, you override its run() method to define the code that will execute concurrently. After creating an instance of your subclass, you call start() rather than run() directly. Calling run() directly executes the method on the current thread without creating a new one, which is a common beginner mistake.
The Thread class provides many useful methods beyond start() and run(). The getName() and setName() methods let you label threads for easier debugging. The getId() method returns a unique long identifier for the thread. The currentThread() static method returns a reference to the thread that is currently executing, which is useful inside run() to access the thread's own state.
Here is a minimal example of extending Thread:
class PrintTask extends Thread { private String message; PrintTask(String message) { this.message = message; } public void run() { for (int i = 0; i < 3; i++) System.out.println(message); } } new PrintTask("Hello").start();
One important method is join(), which blocks the calling thread until the target thread finishes. This is how you wait for background work to complete before continuing. You can also pass a timeout to join() in milliseconds so the calling thread does not wait indefinitely.
The sleep() static method pauses the current thread for a given number of milliseconds. It throws InterruptedException, which must be caught. When a thread calls interrupt() on another thread, it sets an interruption flag. The sleeping thread wakes up and throws InterruptedException, giving it a chance to clean up and exit gracefully.
Extending Thread is simple and direct, but it limits flexibility because Java supports only single inheritance. If your task class already extends another class, you cannot also extend Thread, making the Runnable interface the better choice in most designs.
Interview tip: Explain why calling run() instead of start() does not create a new thread. This tests whether the candidate truly understands the role of the JVM thread scheduler in initiating concurrent execution.
Key Thread Methods Explained
Understanding the Thread class methods is essential for writing correct concurrent Java programs. The most commonly used methods each serve a distinct purpose, and confusing them leads to hard-to-diagnose bugs.
The start() method asks the JVM to create a new thread of execution and schedule it to run the code in run(). It returns immediately; the new thread runs concurrently with the caller. You may only call start() once per Thread instance. Calling it a second time throws IllegalThreadStateException.
The interrupt() method signals a thread that it should stop what it is doing. It does not force the thread to stop; instead, it sets an internal flag that the thread can check using isInterrupted(). If the thread is blocking inside sleep(), wait(), or join(), it will throw InterruptedException, giving it a structured way to exit. Well-written threads periodically check for interruption and shut down cleanly.
The yield() static method hints to the scheduler that the current thread is willing to give up its CPU slot so another thread of equal or higher priority can run. Like thread priority, yield() behavior varies by operating system and should not be used for correctness, only for performance tuning.
The setDaemon(boolean) method must be called before start(). Daemon threads run in the background and are automatically stopped by the JVM when no non-daemon threads remain. Common use cases include garbage collection, background logging, and heartbeat monitors.
Example showing join and interrupt:
Thread worker = new Thread(() -> { try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("Interrupted"); } }); worker.start(); worker.interrupt(); worker.join();
The getState() method returns an enum value from Thread.State representing the current lifecycle state of the thread: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.
Interview tip: Describe what happens to InterruptedException in a run() method. Since run() does not declare checked exceptions, you must catch InterruptedException inside it and typically restore the interrupt flag by calling Thread.currentThread().interrupt() before returning.
Thread Naming and Debugging
Giving threads meaningful names is one of the simplest things you can do to make multithreaded Java programs easier to debug. By default, Java names threads Thread-0, Thread-1, Thread-2, and so on. When you see a stack trace or a thread dump in a profiler, those generic names give you no information about what the thread was supposed to be doing.
You can set a thread name in the constructor or with setName():
Thread t = new Thread(() -> processOrders(), "order-processor-1"); t.start();
When an exception occurs on a named thread, the thread name appears in the stack trace, making it immediately clear which part of your system failed. In a large application with dozens of thread pools, this naming discipline saves hours of debugging time.
Java also provides thread groups via the ThreadGroup class, which lets you organize related threads and perform operations on all threads in a group at once, such as setting priority or interrupting all of them together. While ThreadGroup is considered somewhat outdated compared to ExecutorService, it is still present in the language and appears in older codebases.
Thread dumps are snapshots of every active thread and its current stack trace. You can trigger a thread dump programmatically using Thread.getAllStackTraces(), or externally with tools like jstack or VisualVM. Reading a thread dump is a core debugging skill for diagnosing deadlocks and performance bottlenecks in production Java applications.
Example of printing all active thread names:
Thread.getAllStackTraces().keySet() .forEach(t -> System.out.println(t.getName() + " - " + t.getState()));
Thread-local storage, provided by the ThreadLocal class, allows each thread to have its own independent copy of a variable. This is useful for storing per-request context in web servers, such as user session data, without passing it explicitly through every method call.
Interview tip: Mention that ThreadLocal variables should always be removed after use by calling remove(). Failure to do so in a thread pool environment causes memory leaks because pooled threads are reused and old ThreadLocal values persist into the next task.