Java Notes
Complete guide to the Thread class in Java — constructors, important methods (sleep, join, yield, interrupt), thread naming, thread groups, and practical usage patterns.
The Thread Class Overview
java.lang.Thread is the class that represents a thread of execution. Every thread in Java is an instance of this class (or its subclass).
Thread Constructors
public class ThreadConstructors {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== Thread Constructors ===\n");
// 1. Thread() — default
Thread t1 = new Thread();
System.out.println("Default: " + t1.getName()); // Thread-0
// 2. Thread(Runnable target)
Thread t2 = new Thread(() -> System.out.println(" Running: " + Thread.currentThread().getName()));
System.out.println("With Runnable: " + t2.getName()); // Thread-1
// 3. Thread(Runnable target, String name)
Thread t3 = new Thread(() -> System.out.println(" Running: " + Thread.currentThread().getName()), "MyWorker");
System.out.println("Named: " + t3.getName()); // MyWorker
// 4. Thread(String name)
Thread t4 = new Thread("CustomName");
System.out.println("Name only: " + t4.getName()); // CustomName
// 5. Thread(ThreadGroup, Runnable, String name)
ThreadGroup group = new ThreadGroup("MyGroup");
Thread t5 = new Thread(group, () -> {}, "GroupThread");
System.out.println("With group: " + t5.getName() + " in " + t5.getThreadGroup().getName());
System.out.println("\n--- Starting threads ---");
t2.start();
t3.start();
t2.join();
t3.join();
}
}Output:
| Default | Thread-0 |
| With Runnable | Thread-1 |
| Named | MyWorker |
| Name only | CustomName |
| With group | GroupThread in MyGroup |
| Running | Thread-1 |
| Running | MyWorker |
Important Thread Methods
Thread.sleep() — Pause Execution
public class SleepExample {
public static void main(String[] args) {
System.out.println("=== Thread.sleep() ===\n");
Thread countdown = new Thread(() -> {
try {
for (int i = 5; i > 0; i--) {
System.out.println(" Countdown: " + i);
Thread.sleep(1000); // Sleep 1 second
}
System.out.println(" 🚀 Launch!");
} catch (InterruptedException e) {
System.out.println(" Countdown aborted!");
}
}, "CountdownThread");
System.out.println("Starting countdown...");
long start = System.currentTimeMillis();
countdown.start();
try {
countdown.join();
} catch (InterruptedException e) {}
long elapsed = System.currentTimeMillis() - start;
System.out.println("Total time: " + elapsed + " ms");
System.out.println("\nKey points about sleep():");
System.out.println(" • Static method — always affects CURRENT thread");
System.out.println(" • Throws InterruptedException (must handle)");
System.out.println(" • Does NOT release locks held by the thread");
System.out.println(" • Minimum sleep time (OS may wake later)");
System.out.println(" • Overloads: sleep(millis) and sleep(millis, nanos)");
}
}=== Thread.sleep() === Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Liftoff!
Thread.join() — Wait for Thread to Finish
Output:
Thread.yield() — Hint to Scheduler
=== Thread.yield() === HighPriority: step 1 LowPriority: step 1 HighPriority: step 2 HighPriority: step 3 LowPriority: step 2 HighPriority: step 4 LowPriority: step 3 (yield hint may be ignored by scheduler)
Thread.interrupt() — Signal a Thread to Stop
Output:
Thread Information Methods
public class ThreadInfoMethods {
public static void main(String[] args) throws InterruptedException {
System.out.println("=== Thread Information Methods ===\n");
Thread worker = new Thread(() -> {
try { Thread.sleep(2000); } catch (InterruptedException e) {}
}, "InfoThread");
// Before start
System.out.println("--- Before start() ---");
System.out.println("getName(): " + worker.getName());
System.out.println("getId(): " + worker.getId());
System.out.println("getState(): " + worker.getState()); // NEW
System.out.println("isAlive(): " + worker.isAlive()); // false
System.out.println("isDaemon(): " + worker.isDaemon()); // false
System.out.println("getPriority(): " + worker.getPriority()); // 5
System.out.println("isInterrupted(): " + worker.isInterrupted()); // false
worker.start();
Thread.sleep(100);
// After start
System.out.println("\n--- After start() ---");
System.out.println("getState(): " + worker.getState()); // TIMED_WAITING
System.out.println("isAlive(): " + worker.isAlive()); // true
worker.join();
// After completion
System.out.println("\n--- After completion ---");
System.out.println("getState(): " + worker.getState()); // TERMINATED
System.out.println("isAlive(): " + worker.isAlive()); // false
// Static methods
System.out.println("\n--- Static Methods ---");
System.out.println("currentThread(): " + Thread.currentThread().getName());
System.out.println("activeCount(): " + Thread.activeCount());
}
}=== Thread Information Methods === --- Before start() --- Name: Worker-1 State: NEW Alive: false Daemon: false Priority: 5 --- After start() --- State: RUNNABLE Alive: true --- After join() --- State: TERMINATED Alive: false
Naming and Thread Groups
=== Thread Naming & Groups === DatabaseThread [Group: DB-Pool] - Running CacheThread [Group: Cache-Pool] - Running WorkerThread [Group: Worker-Pool] - Running Thread groups: DB-Pool, Cache-Pool, Worker-Pool
Common Mistakes
1. Calling sleep on a thread object
Thread t = new Thread(() -> { /* work */ });
t.start();
// ❌ WRONG: This sleeps the CURRENT thread, NOT thread t!
t.sleep(1000); // Misleading — compiles but sleeps main thread
// ✅ CORRECT: sleep() is always for the current thread
Thread.sleep(1000); // Clearly shows it affects current thread2. Not handling InterruptedException properly
// ❌ BAD: Swallowing the interrupt
catch (InterruptedException e) { /* ignore */ }
// ✅ GOOD: Either re-interrupt or handle gracefully
catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore flag
return; // Stop the thread
}Interview Questions
Q1: What is the difference between sleep() and wait()?
Answer: sleep() is a Thread static method that pauses the current thread for a fixed duration WITHOUT releasing any locks. wait() is an Object method that releases the object's lock and waits until notify()/notifyAll() is called. sleep() is time-based; wait() is notification-based.
Q2: What does join() do?
Answer: join() makes the calling thread wait until the target thread finishes execution. For example, if main calls t.join(), main blocks until thread t completes. It can accept a timeout parameter.
Q3: What is the purpose of yield()?
Answer: yield() is a hint to the thread scheduler that the current thread is willing to give up its CPU time slice to let other threads of equal priority run. It's just a suggestion — the scheduler may ignore it. The thread goes from RUNNING to RUNNABLE state.
Q4: How do you stop a thread in Java?
Answer: Use interrupt() — set the interrupt flag and check isInterrupted() in the thread's run logic, or catch InterruptedException from blocking methods. Never use deprecated stop() method as it can leave objects in inconsistent states.
Q5: Can we call start() twice on the same thread?
Answer: No. The second call throws IllegalThreadStateException. Once a thread has been started (even if it has finished), it cannot be restarted. Create a new Thread instance instead.
Q6: What is a ThreadGroup?
Answer: ThreadGroup organizes threads into groups for collective management. You can interrupt all threads in a group, set maximum priority, list active threads, etc. However, ThreadGroups are rarely used in modern Java — ExecutorService provides better thread management.
Q8: What is the purpose of Thread.yield()?
A: yield() is a hint to the scheduler that the current thread is willing to yield its current time slice. The scheduler may ignore this hint. It's rarely used in practice because it's unreliable and platform-dependent. It does NOT release any locks.
Q9: What is the difference between sleep() and wait()?
A: sleep() pauses the thread for a specified time without releasing locks. wait() releases the monitor lock and waits until another thread calls notify()/notifyAll(). sleep() is a Thread static method; wait() is an Object instance method that must be called inside synchronized blocks.
Q10: How does thread interruption work in Java?
A: thread.interrupt() sets the thread's interrupt flag. If the thread is sleeping/waiting, it throws InterruptedException and clears the flag. If the thread is running, it must check Thread.interrupted() or isInterrupted() and respond. Interruption is cooperative — it's a polite request, not a forced stop.
Q11: Why was Thread.stop() deprecated?
A: stop() abruptly terminates a thread by throwing ThreadDeath, which can leave shared data in an inconsistent state (partially completed operations, locks released without cleanup). Use interruption instead — it's cooperative, allowing the thread to clean up resources and reach a consistent state before stopping.
Q12: What is the difference between isInterrupted() and Thread.interrupted()?
A: isInterrupted() is an instance method that checks the flag without clearing it (for checking other threads). Thread.interrupted() is a static method that checks AND CLEARS the current thread's interrupt flag. Use interrupted() in the thread that's checking its own status; use isInterrupted() to check another thread.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Thread Class in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, multithreading, thread, class
Related Java Master Course Topics