B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Java Daemon Thread | LiveCodeProgramming

Java Daemon Thread

Daemon threads in Java are background service threads that run in the background. They stop when all user threads finish.

Java में Daemon threads बैकग्राउंड में चलने वाले थ्रेड्स होते हैं। जब सभी user थ्रेड्स समाप्त हो जाते हैं, तो daemon threads भी रुक जाते हैं।

Example: setDaemon(true)

class DaemonDemo extends Thread {
  public void run() {
    if (Thread.currentThread().isDaemon()) {
      System.out.println("This is a daemon thread running...");
    } else {
      System.out.println("This is a user thread.");
    }

    for (int i = 1; i <= 5; i++) {
      System.out.println("Thread step " + i);
      try {
        Thread.sleep(500);
      } catch (Exception e) {}
    }
  }

  public static void main(String[] args) {
    DaemonDemo d = new DaemonDemo();
    d.setDaemon(true); // Set before start
    d.start();

    System.out.println("Main method ends.");
  }
}
Main method ends.
This is a daemon thread running...
Thread step 1
Thread step 2
...

This example shows that the daemon thread may stop when the main method ends, even before completing all steps.

यह उदाहरण दिखाता है कि जैसे ही main method खत्म होती है, daemon thread भी बीच में रुक सकता है।