In Java, threads are classified into User Threads and Daemon Threads based on their role in program execution. Understanding the difference between them is important for managing background tasks and application lifecycle.
- Threads are categorized based on their execution behavior
- User threads perform main tasks, daemon threads support them
- Daemon threads terminate automatically when user threads finish
Daemon Threads
Daemon threads are background threads that provide support services to user threads. They do not prevent the JVM from exiting when all user threads have completed execution.
- Run in the background to support user threads
- Automatically terminate when user threads end
- Created using setDaemon(true) method
class DaemonThreadExample extends Thread{
public void run(){
while (true) {
System.out.println("Daemon thread running...");
}
}
public static void main(String[] args){
DaemonThreadExample t1 = new DaemonThreadExample();
// Set as daemon thread
t1.setDaemon(true);
t1.start();
System.out.println("Main thread ends");
}
}
Output
Main thread ends Daemon thread running... Daemon thread running... Daemon thread running... Daemon thread running... Daemon thread running... Daemon thread running... Daemon thread running... Daemon t...
User Threads
User threads are the main threads that perform the core operations of a program. The JVM continues execution as long as at least one user thread is running.
- Perform primary tasks of the application
- JVM waits for user threads to finish
- Created by default when a thread is instantiated
class UserThreadExample extends Thread{
public void run(){
System.out.println("User thread is running");
}
public static void main(String[] args) {
UserThreadExample t1 = new UserThreadExample();
t1.start(); // By default, it is a user thread
}
}
Output
User thread is running
Daemon Threads Vs User Threads
| Feature | User Thread | Daemon Thread |
|---|---|---|
| Purpose | Performs main application tasks | Handles background/support tasks |
| JVM Behavior | JVM waits for completion | JVM does not wait |
| Execution | Keeps application running | Stops when user threads end |
| Creation | Created by default | Must be set using setDaemon(true) |
| Example | Main thread, worker threads | Garbage Collector, background services |