Threads — Creating & Managing
A thread is the smallest unit of execution. Java runs each program on the main thread; you can create additional threads for concurrent work. Threads share the JVM's heap memory — this is powerful but dangerous without proper synchronisation.
Thread Creation — Three Ways
public class ThreadCreation {
public static void main(String[] args) throws InterruptedException {
// 1. Extend Thread (not recommended — prevents extending other classes)
class BookLoader extends Thread {
@Override
public void run() {
System.out.println("Loading books on: " + Thread.currentThread().getName());
}
}
new BookLoader().start(); // start() creates new thread; DON'T call run() directly
// 2. Implement Runnable (preferred for class-based approach)
Runnable catalogTask = new Runnable() {
@Override
public void run() {
System.out.println("Building catalog on: " + Thread.currentThread().getName());
}
};
new Thread(catalogTask, "catalog-thread").start();
// 3. Lambda Runnable (cleanest — most common)
Thread emailThread = new Thread(() -> {
System.out.println("Sending email on: " + Thread.currentThread().getName());
}, "email-thread");
emailThread.start();
// Thread control
Thread t = new Thread(() -> {
for (int i = 0; i < 5; i++) {
System.out.println("Working... " + i);
try { Thread.sleep(100); } catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore interrupt flag
return; // exit gracefully
}
}
});
t.setDaemon(false); // daemon thread: JVM exits when only daemons remain
t.setPriority(Thread.NORM_PRIORITY); // 1 (MIN) to 10 (MAX)
t.start();
t.join(); // wait for t to finish before main continues
System.out.println("Main: all threads done.");
// Thread states: NEW → RUNNABLE → BLOCKED/WAITING/TIMED_WAITING → TERMINATED
System.out.println("Thread state: " + t.getState()); // TERMINATED
}
}Thread Lifecycle
- NEW — Thread created but start() not called.
- RUNNABLE — Running or waiting for CPU (both in Java's RUNNABLE).
- BLOCKED — Waiting for a monitor lock (synchronized).
- WAITING — Waiting indefinitely: wait(), join(), LockSupport.park().
- TIMED_WAITING — Waiting with timeout: sleep(ms), wait(ms), join(ms).
- TERMINATED — run() method completed or exception thrown.
Quick Quiz
Tip
Tip
Practice Threads Creating Managing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Async code runs non-blocking — callbacks, promises, and async/await
Practice Task
Note
Practice Task — (1) Write a working example of Threads Creating Managing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Threads Creating Managing is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- A thread is the smallest unit of execution.
- NEW — Thread created but start() not called.
- RUNNABLE — Running or waiting for CPU (both in Java's RUNNABLE).
- BLOCKED — Waiting for a monitor lock (synchronized).