Skip to content

Commit 1d23c9e

Browse files
committed
feat: Demonstrate daemon threads in Java
WHAT the code does: - Defines DemonThread extending Thread: - run() loops infinitely, printing "Hello World!". - In main(): - Creates DemonThread instance D. - Marks D as daemon using setDaemon(true). - Starts D with start(), moving it into runnable state. - Prints "Main done" and then main thread terminates. WHY this matters: - Shows how daemon threads differ from user threads. - JVM automatically terminates daemon threads when all user threads finish. - Demonstrates background task behavior (like garbage collector, monitoring, or housekeeping). - Reinforces lifecycle concepts: even infinite loop threads can be stopped once only daemons remain. HOW it works: 1. D is created and configured as a daemon thread. 2. D.start() schedules D to run concurrently. 3. main() prints "Main done" and ends. 4. JVM sees only daemon threads remain → shuts down process, killing daemon thread. 5. Output: "Hello World!" may print a few times, but stops once main exits. Tips and gotchas: - Must call setDaemon(true) before start(); calling it after throws IllegalThreadStateException. - Daemon threads are not guaranteed to finish tasks, so avoid them for critical work. - Best used for background services that support user threads but don’t need to live beyond them. - Don’t rely on daemon thread output consistency; it may terminate abruptly. Use-cases / analogies: - Daemon threads = janitors/housekeepers who clean up as long as the office is open (user threads active). - Common in loggers, background resource monitoring, or async cache refreshers. - JVM’s garbage collector itself runs as a daemon. Short key: java daemon-threads background-task lifecycle jvm-termination. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 4cf8308 commit 1d23c9e

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed
Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
//Demon Threads are working in BackGround is called Demon Threads.
21
public class DemonThread extends Thread {
3-
public void run(){
4-
while(true)
5-
{
2+
public void run() {
3+
while(true) {
64
System.out.println("Hello World!");
75
}
86
}
9-
107
public static void main(String[] args) {
118
DemonThread D = new DemonThread();
129
D.setDaemon(true);
1310
D.start(); //Runnable ne start keya and runnable state mai Dala.
1411
System.out.println("Main done");
1512
}
1613
}
14+
15+
//Demon Threads are working in Background is called Demon Threads.

0 commit comments

Comments
 (0)