Daemon Thread in Java — Java Technical Interview Questions & Answers
Daemon Thread in Java
Daemon Thread in Java
- Daemon Thread is part of Java concurrency. A thread is a path of work inside a process. Create with Thread or Runnable, then call start() — not run(). run() only runs on the same thread.
- For Daemon Thread: if two threads share data, synchronize or the result can be wrong. sleep pauses. join waits for another thread to finish. daemon threads die when all user threads finish.
- Daemon Thread deadlock: two threads wait for each other’s lock forever. Avoid by locking in the same order. Don’t guess thread order — it can change every run.
- Let's take this on the board with one tiny Main class — no extra files. Daemon Thread in Java — start() schedules the thread; main also prints — order may vary. Start from main, go line by line, and stop at each print. That output is the proof for Daemon Thread.
Technical Interview Tip: start() vs run() is a classic interview question.
Code Examples for Daemon Thread in Java
Example
// Thread demo
public class Main {
public static void main(String[] args) {
Thread t = new Thread(() -> System.out.println("Hi from thread"));
t.start();
System.out.println("Hi from main");
}
}Daemon Thread in Java — start() schedules the thread; main also prints — order may vary.
How to Explain Daemon Thread in Java to an Interviewer
What is Daemon Thread?
Daemon Thread — thread = one path of work. start() schedules it. run() does not. Daemon Thread — shared data needs synchronization. Daemon Thread — sleep = pause. join = wait for other thread.
Why do we use Daemon Thread in Java?
Makes the program clearer or safer Daemon Thread — thread = one path of work. start() schedules it. run() does not.
Write one small example of Daemon Thread.
Show syntax Say what prints
What mistake do beginners make with Daemon Thread?
Only the name, no example Daemon Thread — calling run() instead of start(). Deadlock = locks in wrong order.
Where is Daemon Thread used in a real program?
Day-to-day Java code