Threads Types¶
Short answer: 2 main types But like most things in Java, thereβs a deeper layer if you peek under the hood π
π§ 1. User Threads (a.k.a. Non-Daemon Threads)¶
These are the main actors on stage π
- Created by your application
- JVM waits for them to finish
- Keep the program alive
π Examples:
main()thread- Worker threads
- Business logic threads
π 2. Daemon Threads¶
These are the background workers π οΈ
- Run in background
- JVM does NOT wait for them
- Die automatically when all user threads finish
Thread t = new Thread(() -> {
while (true) {
System.out.println("Daemon working...");
}
});
t.setDaemon(true);
t.start();
π Examples:
- Garbage Collector thread
- JVM housekeeping threads
βοΈ User vs Daemon¶
| Feature | User Thread π§ | Daemon Thread π |
|---|---|---|
| Purpose | Main work | Background work |
| JVM waits? | β Yes | β No |
| Lifecycle | Independent | Depends on user threads |
π§ Internal JVM Threads (bonus insight)¶
Even if you donβt create threads, JVM already runs some:
- Garbage Collector
- JIT Compiler
- Signal Dispatcher
π Most of these are daemon threads
β οΈ Important Rule¶
π Must be called before start()
Otherwise β IllegalThreadStateException
π― Interview Answer¶
Java has two main types of threads: User threads and Daemon threads. User threads perform main application tasks and keep JVM alive, while daemon threads run in the background and terminate when all user threads finish.
π§ Memory Trick¶
User Thread = Life of program π§ Daemon Thread = Support system π
If you want deeper:
- Thread lifecycle (NEW β RUNNABLE β BLOCKED...)
- Or how threads actually map to OS threads (important for interviews)