Multithreading
Thread Methods
Deep dive into core thread methods: start(), run(), sleep(), join(), yield(), and interrupt().
Interview: Commonly tests how to properly manage thread execution and handle the InterruptedException properly.
The Thread class exposes critical API methods that allow controlling thread execution, yielding CPU resource, blocking for other threads, and coordinating thread shutdown via interruption.
Core Idea
Thread control requires understanding blocking APIs (sleep, join) and cooperative signaling (interrupt).
Why It Matters
Improperly handling thread blocking leads to frozen operations or hard-to-kill tasks.
Interview Lens
Expect questions on why sleep() doesn't release locks, how interrupt() behaves, and how to stop a thread safely.
Key Thread Methods
sleep(long millis): Pauses execution of the current thread. Crucially, it does NOT release any monitor locks.join(): Suspends the calling thread until the target thread finishes execution.yield(): Suggests to the OS scheduler that the current thread is willing to yield its current CPU time slice. The scheduler is free to ignore this hint.interrupt(): Sends a signal to the target thread to stop what it is doing. If the thread is blocked insleep(),join(), orwait(), it wakes up and throws anInterruptedException, clearing its interrupt flag. If it is running, the interrupt flag is set to true.
Code Walkthrough
This program demonstrates how to interrupt a thread that is sleeping and how to handle the interruption gracefully.
public class ThreadMethodsDemo { public static void main(String[] args) throws InterruptedException { Thread worker = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { System.out.println("Working..."); try { Thread.sleep(1000); // Throws exception if interrupted while sleeping } catch (InterruptedException e) { System.out.println("Interrupted during sleep. Cleaning up..."); // Re-set interrupt flag to propagate status Thread.currentThread().interrupt(); } } System.out.println("Worker thread exiting cleanly."); });
worker.start(); Thread.sleep(2500); // Let worker run for a bit System.out.println("Requesting interruption..."); worker.interrupt(); // Signal worker thread worker.join(); // Wait for worker to exit System.out.println("Main thread done."); } }
Interview-Relevant Information
Q: How do you stop a thread safely in Java?
Answer: Do not use deprecated methods like Thread.stop(), which release all monitor locks immediately, causing data corruption. Instead, use a cooperative cancellation mechanism. You can use an internal volatile boolean flag or query the thread's native interrupt status (Thread.currentThread().isInterrupted()) to exit the run() method loop cleanly.
Quick Checklist
Why does sleep() not release locks? What does worker.join() do? How does interrupt() behave on a running vs. a blocked thread? If yes, you have mastered the basic Thread APIs.
Use Cases
Scheduling simple delay tasks in command-line utilities.
Coordinating worker exit before finishing the main execution thread.
Common Mistakes
Swallowing InterruptedException (empty catch block), which prevents thread cancellation mechanisms from working.
Thinking Thread.sleep() yields monitor locks. It preserves all held monitors.