Daemon Thread in Java


Daemon Thread in Java

In Java, a daemon thread is a thread that runs in the background and does not prevent the Java Virtual Machine (JVM) from exiting when all non-daemon threads have completed their execution. Daemon threads are typically used for background tasks or services that can be terminated when the main application or other non-daemon threads finish their execution.


Example 01:

package com.java.Multi_threading;

public class DaemonThreadExample {

public static void main(String[] args) {

// Create a daemon thread

Thread daemonThread = new Thread(new DaemonTask());

// Set the thread as daemon

daemonThread.setDaemon(true);

// Start the daemon thread

daemonThread.start();

// Main thread sleeps for a while

try {

Thread.sleep(3000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println("Main thread exiting. Daemon thread will be terminated.");

}

}


class DaemonTask implements Runnable {

@Override

public void run() {

while (true) {

System.out.println("Daemon thread is running...");

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

Post a Comment

0 Comments