Threads
TL;DR
- A Thread is the smallest unit of execution within a process.
- Java applications start with a single “main” thread, but can spawn multiple threads to perform tasks concurrently.
- Concurrency improves application performance by utilizing multiple CPU cores.
Concept
In a standard Java application, the code executes sequentially. Line 1 executes, then Line 2, etc. If Line 3 requires a massive database download (taking 5 seconds), the entire application freezes and waits for it to finish before moving to Line 4.
By introducing Threads, you can tell Java to run Line 3 in the background on a completely separate thread. This allows the main thread to immediately continue executing Line 4, keeping your application responsive.
Threads within the same Java application (the same Process) share the same memory space (the Heap), but each thread has its own private Stack memory to track its method calls and local variables.
Examples
public class ThreadBasics {
public static void main(String[] args) {
// 1. Identify the current executing thread
Thread mainThread = Thread.currentThread();
System.out.println("Current thread: " + mainThread.getName()); // "main"
// 2. Create and start a new background thread
Thread workerThread = new Thread(() -> {
System.out.println("Hello from: " + Thread.currentThread().getName());
try {
// Pause this thread for 2 seconds
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Worker thread finished!");
}, "Worker-1");
workerThread.start(); // START the thread (Don't call run()!)
System.out.println("Main thread is not blocked!");
}
}
Interview Questions
Q: What is the difference between thread.start() and thread.run()?
A: This is a classic trap. Calling thread.start() tells the JVM to allocate a new, separate call stack and execute the thread’s run method asynchronously in the background.
If you accidentally call thread.run(), the JVM does not create a new thread. It simply executes the code inside run() synchronously on the current thread, completely defeating the purpose of multithreading.
Q: What is a Daemon Thread?
A: A Daemon Thread is a low-priority background thread that provides services to user threads (like the Garbage Collector). The key distinction is that the JVM will not wait for daemon threads to finish. When all standard “User Threads” (like the main thread) complete their execution, the JVM will immediately terminate and kill any remaining daemon threads. You can make a thread a daemon by calling thread.setDaemon(true) before starting it.